javascript cookies save and load
I have this javascript code that changes the style of the website. but this code changes the style only when you click on it. and after you refresh the page it returns to default. I want it to save the users preferences. I really like the code and I do not want to change it with another one. can you please help. I want you to give me the code after adding the cookies code to it!
$(document).ready(function() {
$("#fullswitch").click(function() {
$("#chpheader").removeClass("compact");
$("#imgg").removeClass("compact");
$("#chpheader").removeClass("original");
$("#imgg").removeClass("original");
开发者_Python百科 $("#chpheader").addClass("normal");
$("#imgg").addClass("normal");
});
$("#compactswitch").click(function() {
$("#chpheader").addClass("compact");
$("#imgg").addClass("compact");
$("#chpheader").removeClass("original");
$("#imgg").removeClass("original");
$("#chpheader").removeClass("normal");
$("#imgg").removeClass("normal");
});
$("#originalswitch").click(function() {
$("#chpheader").addClass("original");
$("#imgg").addClass("original");
$("#chpheader").removeClass("compact");
$("#imgg").removeClass("compact");
$("#chpheader").removeClass("normal");
$("#imgg").removeClass("normal");
});
});
You're doing it wrong. You should add a class to a top-level element such as the root (<html>
) and style the rest of your document according to that.
.style1-p {
background: blue;
}
.style1-div {
background: red;
}
Should become
.style1 p {
background-blue;
}
.style1 div {
background-red;
}
That way, you only need to change one class, and the whole document will change. It will also mean you only need to save one cookie (that describes that one class), and load it only once.
jsFiddle Example
EDIT: jsFiddle example updated to include Cookies.
EDIT2: jsFiddle example updated to include multiple stylings!
A cookie is just a key value pair so you can have one cookie per element you are styling where the key is the id and the value is the class name. In jQuery you would set them like this:
$("#chpheader").removeClass("compact");
$.cookie("chpheader", $("#chpheader").attr('class'));
and then at the top of your doc ready you would have:
$(document).ready(function() {
if($.cookie("#chpheader")) {
$("#chpheader").set("className", $.cookie("#chpheader"));
}
....
but word of warning, your code is already a little messy, if you go in and start setting and unsetting cookies all over the place things are going to get really sloppy. I would recommend trying to pull out some functions, and set up the observer pattern. Also, do you really need a normal class? and if you do do you really need to get rid of it when you add the compact class?
精彩评论