Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I've created a button using js to narrow or widen the width of page but not working

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

       <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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading