user3473897
user3473897

Reputation: 11

How to set a permanent background color with a script

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

Answers (3)

adeneo
adeneo

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>

FIDDLE

Upvotes: 0

Bogdan Iulian Bursuc
Bogdan Iulian Bursuc

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

Niet the Dark Absol
Niet the Dark Absol

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

Related Questions