My project has the option to change the site theme by clicking on a link:
Localstorage will provide you a possibilty to store the data without expiration-date:
$('.change-theme').click(function () {
$('body').toggleClass('theme-dark');
if($('body').hasClass('theme-dark')){
localStorage.setItem('theme', 'theme-dark');
}
});
$(document).ready(function(){
var theme = localStorage.getItem('theme');
if(theme !== ''){
$('body').addClass(theme);
}
});
Whereas sessionStorage
will store the data only for one session, until the browser is closed (usage is the same as localStorage
).
All major Browser support this feature, the Internet Explorer support this since version 8.
Note: you can only store strings in the Webstorage.
If you want to use cookies instead you can try:
document.cookie="theme=theme-dark"; //setter
and
var x = document.cookie; //getter
Reference
webStorage
cookies