Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 639
user2379090 Avatar asked Feb 02 '26 01:02

user2379090


2 Answers

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

like image 108
Oriol Avatar answered Feb 03 '26 13:02

Oriol


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.

like image 20
T.J. Crowder Avatar answered Feb 03 '26 13:02

T.J. Crowder