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

161
Visualizações
Toggle button : Javascript toggle doesn't works locally

I try to create a toggle button in order to show/hide some content. For the moment, I use that :

// test.js

var toggle = document.getElementById("toggle");
var content = document.getElementById("content");

toggle.addEventListener("click", function() {
  content.style.display = (content.dataset.toggled ^= 1) ? "block" : "none";
});
#content {
  display: none;
}
<!DOCTYPE html>
<html>

<head>
  <link rel="stylesheet" href="style.css">
  <script type="text/javascript" src="test.js"></script>
</head>

<body>
  <button id="toggle">Click Me</button>
  <div id="content">Hello World</div>
</body>

</html>

If I use these code with codepen or JSFiddle, all works fine, but when I try it locally, ( when I click on my index.html file, open it with firefox or an other browser ) my button "Click Me" doesn't works.

When I click on it, nothing happens...

Someone to show me why ?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You could make your function to be fired on load event.

Possible example

(function() {
  var loadedContent = {
    init: function() {
      window.addEventListener("load", function(event) {
        var toggle = document.getElementById("toggle");
        var content = document.getElementById("content");

        toggle.addEventListener("click", function() {
          content.style.display = (content.dataset.toggled ^= 1) ?
            "block" :
            "none";
        });
      });
    }
  };
  loadedContent.init();
})();
#content {
  display: none;
}
<button id="toggle">Click Me</button>
<div id="content">Hello World</div>

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