user2379090
user2379090

Reputation: 123

Does anyone know how to store a css change made by javascript function locally?

I have been scratching my head for a while, and I can't figure out how I could locally store (HTML5 local storage) a change to the styling of a certain div made by a javascript function. I have a button which allows the user to change the background colour of the container by changing the css (inline). Does anyone know of a way of storing this change?

Upvotes: 3

Views: 1327

Answers (3)

Oriol
Oriol

Reputation: 288100

Demo

JS (running at load or DOMContentLoaded):

var bgColor = document.getElementById('bgcolor');
bgColor.onchange = function() {
    document.body.style.backgroundColor = this.value;
    localStorage.setItem('bgColor', this.value);
};
bgColor.value = localStorage.getItem('bgColor');
bgColor.onchange();

HTML:

<input id="bgcolor" />

Or, if you use jQuery,

$('#bgcolor')
    .val(localStorage.getItem('bgColor'))
    .change(function() {
        $('body').css({'background-color': this.value});
        localStorage.setItem('bgColor', this.value);
    })
    .change();

Demo

Upvotes: 2

T.J. Crowder
T.J. Crowder

Reputation: 1074238

So you have a function like:

function changeDivBackground(div, bg) {
    /* ...change the background... */
}

There are two steps:

  1. Remember the value:

    function changeDivBackground(div, bg) {
        /* ...change the background... */
    
        localStorage["theDivBackground"] = bg;
    }
    
  2. In a script tag at the end of the page, see if you have a value and use it:

    var bg = localStorage["theDivBackground"];
    if (bg) {
        changeDivBackground(/*...get the div...*/, bg);
    }
    

The script tag is at the end of the page in #2 so that the div will exist by the time it's run.

Upvotes: 2

Cole
Cole

Reputation: 1503

Store the value to local storage. Then write a JavaScript function that retrieves the value and applies it.

Upvotes: -1

Related Questions