I have many buttons that change/add/remove elements. Some of the elements are dynamic e.g. clicking button one will create button two etc.
I'd like to save the state of the buttons/page in local storage. If I clicked button one, and then two, the background is now red. When the visitor returns (after browser close) it will be as if they have already clicked one>two and will see the red background as before.
I've been reading Mozilla setItem and every post on Stackoverflow about local storage but I can't find any examples of this exact scenario. https://jsfiddle.net/oh9q2Lzw/1/
$('.one').on('click', function() {
$('.blue').removeClass('blue').addClass('green');
});
$('.two').on('click', function() {
$('.green').removeClass('green').addClass('red');
});
button {
padding: 10px 40px;
}
.blue {
width: 200px;
padding: 20px;
background: blue
}
.green {
width: 200px;
padding: 20px;
background: green
}
.red {
width: 200px;
padding: 20px;
background: red
}
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.js"></script>
<br>
<div class="box">
<button class="one">one</button>
<button class="one">one</button>
<button class="two">two</button>
</div>
<br>
<div class="blue"></div>
<br>
<div class="blue"></div>
In your example, the only memory the page needs is the class name of the divs applied when the style was last changed.
Therefore, the simple solution is to store the class name in local storage each time it changes by modifying your button events as follows:
$('.one').on('click', function() {
$('.blue').removeClass('blue').addClass('green');
localStorage.setItem("div-class", "green");
});
$('.two').on('click', function() {
$('.green').removeClass('green').addClass('red');
localStorage.setItem("div-class", "red");
});
When the page loads, the hard-coded class is always "blue" and so this can be changed if a value is stored in local storage.
This is done by adding a function to the window.onload event:
window.onload = function() {
if (localStorage.getItem("div-class")) {
$('.blue').removeClass('blue').addClass(localStorage.getItem("div-class"));
}
};
The SO snippet tool doesn't allow local storage access but I've modified your JS fiddle with a working example: https://jsfiddle.net/g5wqjo2h/
I've also made a modified version with an extra button to allow you to clear localStorage during development. If the clear memory button is clicked, when the js Fiddle is next run or loaded, the divs return to the default blue class. Otherwise, the previous colour is loaded from localStorage. : https://jsfiddle.net/g5wqjo2h/1/