What’s the problem here?
It correctly works when onload function runs but not when myFunction runs.
JS file with defer attribute inside <head> :
let cont = document.getElementsByClassName("container")[0];
let isit = localStorage.getItem("isit");
let button = document.getElementById("nawi");
window.onload = function () {
if (isit == null) {
localStorage.setItem("isit", 0);
}
if (isit == 0) {
cont.style.width = "100%";
localStorage.setItem("isit", 0);
button.innerHTML = "Make it narrow";
console.log(isit);
} else {
cont.style.width = "1000px";
localStorage.setItem("isit", 1);
button.innerHTML = "Make it wide";
console.log(isit);
}
};
function myFunction() {
if (isit == 0) {
cont.style.width = "1000px";
localStorage.setItem("isit", 1);
button.innerHTML = "Make it wide";
console.log(isit);
}
if (isit == 1) {
cont.style.width = "100%";
localStorage.setItem("isit", 0);
button.innerHTML = "Make it narrow";
console.log(isit);
}
}
HTML file:
<button onclick="myFunction()" id="nawi"></button>
>Solution :
When you click the button you aren’t changing the value of the variable isit
This means that although you are changing the localStorage value it is not reflected in the JavaScript so it is running the same section of the if statement each time you click the button.
Change the function to this.
function myFunction() {
if (isit == 0) {
cont.style.width = "1000px";
localStorage.setItem("isit", 1);
button.innerHTML = "Make it wide";
console.log(isit);
}
else {
cont.style.width = "100%";
localStorage.setItem("isit", 0);
button.innerHTML = "Make it narrow";
console.log(isit);
}
isit = localStorage.getItem("isit");
}
Currently what happens is it checks to see if isit == 0 and then chang