Reputation: 123
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
Reputation: 288100
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();
Upvotes: 2
Reputation: 1074238
So you have a function like:
function changeDivBackground(div, bg) {
/* ...change the background... */
}
There are two steps:
Remember the value:
function changeDivBackground(div, bg) {
/* ...change the background... */
localStorage["theDivBackground"] = bg;
}
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
Reputation: 1503
Store the value to local storage. Then write a JavaScript function that retrieves the value and applies it.
Upvotes: -1