Reputation: 11
my goal is quite simple. I have a script which changes the backgroud color by a click and returns the color to the basic one with the second click.
CSS
body {
background-color: white;
}
.negative {
background-color: black;
}
Javascript
$(zasuvka).click(function(){
$("body").toggleClass(negative);
});
When I am going throught the webpage, I mean when I am clicking on the menu links of my webpage (contact, gallery..), the background color is returning to the basic one. I want to make the script permanent till the button which runs this script is pressed again. I hope you get it. Thanks a lot for help.
Upvotes: 0
Views: 412
Reputation: 318232
<script>
var bg = localStorage.getItem('bg');
if (bg && bg == 'neg') $('body').addClass('negative');
$('#zasuvka').click(function(){
$("body").toggleClass('negative');
localStorage.setItem('bg', (bg&&bg=='neg') ? 'norm' : 'neg');
});
</script>
Upvotes: 0
Reputation: 2275
Use jquery cookie https://github.com/carhartl/jquery-cookie to save the state between requests than check the status on refresh.
Upvotes: 0
Reputation: 324650
Consider using localStorage
to save the toggle status of the class, then set it anew on page load. Keep in mind, however, that this will risk a FOUC (Flash of unstyled content) in that the background will be white until the script loads, after which it may suddenly change to black. You could alternatively save the value in a cookie and use server-side code to set the initial background colour.
Upvotes: 2