Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

98
Views
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:

       <button onclick="myFunction()" id="nawi"></button>
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!