Sudip Bose
Sudip Bose

Reputation: 11

html5 - Hold page background color even after page refresh using local storage

I want to keep a background color value even after page refresh. I think it is possible with html5 localstorage or jquery ajax.can you please help me out to make this things.

Below is the code that i've tried so far:

HTML

<ul class="chngeme">
    <li class="red"></li>
    <li class="blue"></li>
    <li class="green"></li>
</ul>

JS

$('ul.chngeme li').click(function() {
    var getcolor = $(this).css('background-color');

    $('body').css('background', getcolor);

    if (typeof(Storage) !== 'undefined') {
        // Store
        localStorage.setItem('colorvalue', getcolor);

        // Retrieve
        document.getElementById('body').style.setProperty = localStorage.getItem('colorvalue');
    }else {
        document.getElementById('result').style.setProperty = 'Sorry, your browser does not support Web Storage...!';
    }
});

Thanks in advance!

Upvotes: 0

Views: 412

Answers (1)

Kesavamoorthi
Kesavamoorthi

Reputation: 969

You have to store the value when the user clicks on the li. But you have to retrieve the value when the page/document loads.

Use the below code snippet:

HTML

<ul class="chngeme">
    <li class="red"></li>
    <li class="blue"></li>
    <li class="green"></li>
</ul>

CSS

.red {
    background-color: #f00;
}

.blue {
    background-color: #00f;
}

.green {
    background-color: #0f0;
}

JS

$('ul.chngeme li').click(function() {
    var color = $(this).css('background-color');

    $('body').css('background-color', color);

    if (typeof(Storage) !== 'undefined') {
        // Store
        localStorage.setItem('colorvalue', color);
    }else {
        $('#result').html('Sorry, your browser does not support Web Storage...!');
    }
});

$(document).ready(function() {
    if (typeof(Storage) !== 'undefined') {
        // Retrieve
        var color = localStorage.getItem('colorvalue');

        $('body').css('background-color', color);
    }else {
        $('#result').html('Sorry, your browser does not support Web Storage...!');
    }
});

Here is the fiddle: http://jsfiddle.net/k7moorthi/bqwhwrv6/

Upvotes: 2

Related Questions