Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

100
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda