Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

99
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda