Reputation: 43
I am trying to figure out how to store DOM changes done with vanilla JavaScript in local storage but so far unable to figure it out.
This is a short cut out from the JavaScript code that do several more changes to the DOM.
The function is called by a button on the webpage.
function myFunction()
{
document.body.style.backgroundColor = "black";
var element = document.getElementsByTagName('input');
for (var i = 0; i < element.length; i++) {
element[i].style.color = "black";
element[i].style.backgroundColor = "#565969";
element[i].style.borderColor = "black";
element[i].style.boxShadow = "inset 0 0 5px black";}
}
Have seen it is easier with two CSS to shift between, but would like to know how to solve the problem above.
Upvotes: 1
Views: 1905
Reputation: 2753
You can check localstorage for the DOM values first, if its there you make use of it otherwise you apply new DOM values.
function myFunction() {
var DOMValues = {};
var storageContent = localStorage.getItem('cssProps');
if (storageContent) {
DOMValues = JSON.parse(storageContent);
manipulateDOM(DOMValues);
} else {
DOMValues = {
backgroundColor: 'blue',
color: 'black'
};
localStorage.setItem('cssProps', JSON.stringify(DOMValues));
manipulateDOM(DOMValues);
}
}
function manipulateDOM (props) {
document.body.style.backgroundColor = props.backgroundColor;
var element = document.getElementsByTagName('input');
for (var i = 0; i < element.length; i++) {
element[i].style.color = props.color;
element[i].style.backgroundColor = props.backgroundColor;
}
}
Upvotes: 1