user5934139
user5934139

Reputation:

jQuery style switcher with cookie

I don't have much experience with JavaScript but I'm getting into jQuery and learning along the way. I have a style sheet switcher (or theme switcher) on my page, but it switches to the default stylesheet on refresh/visiting a different page.

I know cookies are used for this, but don't know how to implement it into my code...

<link rel="stylesheet" type="text/css" href="css/light-theme.css"> (in my head tag, html)

jQuery:
$('#dark').click(function (){
   $('link[href="css/light-theme.css"]').attr('href','css/dark-theme.css');
});
$('#light').click(function (){
   $('link[href="css/dark-theme.css"]').attr('href','css/light-theme.css');
});

Thanks for the help guys.

Upvotes: 2

Views: 832

Answers (1)

Eric Guan
Eric Guan

Reputation: 15982

I'm sure you can do it with cookies, but i'll try it with HTML5 local storage

jQuery:

$('#dark').click(function (){
   $('link[href="css/light-theme.css"]').attr('href','css/dark-theme.css');
   localStorage.stylesheet = 'css/dark-theme.css';
});
$('#light').click(function (){
   $('link[href="css/dark-theme.css"]').attr('href','css/light-theme.css');
   localStorage.stylesheet = 'css/light-theme.css';
});

Not sure if you have to wait for document ready or not in order to access the stylesheet.

$(document).ready(function(){
     if(localStorage.stylesheet !== null){
         //check which stylesheet is active
         if($('link[href="css/dark-theme.css"]').length>0){
               $('link[href="css/dark-theme.css"]').attr('href',localStorage.stylesheet);
         }else if($('link[href="css/light-theme.css"]').length>0){
               $('link[href="css/dark-theme.css"]').attr('href',localStorage.stylesheet);
         }

    }
})

You'll have better browser compatibility with cookies though. The browser may not support localStorage.

if(typeof(Storage) !== "undefined") {
    // Code for localStorage/sessionStorage.
} else {
    // Sorry! No Web Storage support..
}

Upvotes: 1

Related Questions