mrmozer - As Nile said, you'll need to set a cookie to remember the user's preference. Here's how you would do that.
For convenience, add these 2 functions from the w3schools site, getCookie() and setCookie(), to the top of your JS file:
Code:
function getCookie(c_name)
{
if (document.cookie.length>0)
{
c_start=document.cookie.indexOf(c_name + "=");
if (c_start!=-1)
{
c_start=c_start + c_name.length+1;
c_end=document.cookie.indexOf(";",c_start);
if (c_end==-1) c_end=document.cookie.length;
return unescape(document.cookie.substring(c_start,c_end));
}
}
return "";
}
function setCookie(c_name,value,expiredays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate()+expiredays);
document.cookie=c_name+ "=" +escape(value)+
((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}
Then in the jQuery functions that changes stylesheets, save the user's preference like this (the green line was added to your original code):
Code:
// blue
$("#css-blue").click(function() {
$("link[rel=stylesheet]").attr({href : "CSS/layout_blue.css"});
setCookie('csspref', 'blue');
});
(repeat for the other colors)
Finally, check to see if the cookie is set when the page loads, and change to the user's preferred stylesheet if they've chosen one.
Put this code at the end of your $(document).ready() function:
Code:
var $cssPref = getCookie('csspref');
if ($cssPref.length > 0)
{
$('#css-' + $cssPref).trigger('click');
}
That should do it! A better solution would be to check the cookie when rendering the page and simply include the correct stylesheet, instead of changing it via JS when the page loads. In PHP that would look something like this:
PHP Code:
<?php
$cssFile = 'red.css'; // default stylesheet
if (isset($_COOKIE['csspref']) && in_array($_COOKIE['csspref'], array('blue', 'green')))
{
$cssFile = $_COOKIE['csspref'] . '.css';
}
echo '<link rel="stylesheet" media="screen" type="text/css" href="CSS/layout_' . $cssFile . '" />';
?>
Hope that helps!
By the way, the code you're using has a big problem: it would change out the href of every single stylesheet you've got loaded. If you have more than one this is going to be a problem.
You can fix it by giving an id to the stylesheet you want to change out, like this:
HTML Code:
<link id="changeableStylesheet" href="CSS/layout_blue.css" rel="stylesheet" type="text/css" />
And then in your functions that change out the stylesheets, change the selector like this:
This:
Code:
$("link[rel=stylesheet]").attr({href : "CSS/layout_red.css"});
Becomes:
Code:
$("#changeableStylesheet").attr({href : "CSS/layout_red.css"});
Bookmarks