I want Local Storage , I selected but now I want to add local Storage to it so it remembers when I leave the page
I made now this code but it doesn’t seem to work properly, could someone please help me ?
HTML
<div class="d-flex align-items-center me-4">
<span class="input-group-text d-inline-flex">Màu nền</span>
<div class="ms-2">
<button class="border border-dark btn btn-primary p-3 btn-background" id="blue" data-value="blue"></button>
<button class="border border-dark btn btn-light p-3 btn-background" id="white" data-value="white"></button>
<button class="border border-dark btn btn-success p-3 btn-background" id="green" data-value="green"></button>
<button class="border border-dark btn btn-warning p-3 btn-background" id="gold" data-value="gold"></button>
<button class="border border-dark btn btn-danger p-3 btn-background" id="red" data-value="red"></button>
</div>
</div>
JQUERY
$(document).ready(function () {
/* =============================== BACKGROUND COLOR =================================*/
$(".btn-background").click(function () {
var btnBackGround = $(this).attr('data-value');
console.log(btnBackGround);
var btnBG = JSON.parse(localStorage.getItem("btnBG")) || [];
btnBG.push({
btnBG: btnBackGround
})
$(".btn-background").each(function () {
if (btnBackGround == "blue") {
$("#content").css("background-color", "blue");
}
if (btnBackGround == "white") {
$("#content").css("background-color", "white");
}
if (btnBackGround == "green") {
$("#content").css("background-color", "green");
}
if (btnBackGround == "gold") {
$("#content").css("background-color", "gold");
}
if (btnBackGround == "red") {
$("#content").css("background-color", "red");
}
localStorage.setItem("btnBG", JSON.stringify(btnBG));
})
})
}
2
Answers
As I can see, you are making an array of colors but your intention is just use one, so instead of:
you should ask for the local storage as a default string:
This also changes the way you define the variable:
Replaced for:
And, to keep the value on reload, you are just using onclick. The load of the variable has to come after
ready
:you can study this example https://jsbin.com/xomuyirodi/3/edit?html,css,js,output
HTML
JS