2

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 ?

secan
  • 2,157
  • 1
  • 4
  • 21
Drak432
  • 143
  • 6
  • 2
    Try moving `` at the end of the body, right before the closing `` tag. In this way you are sure the JavaScript code will be executed only after the DOM has loaded and all HTML elements you want to manupulate are in the page. – secan Aug 03 '21 at 13:51
  • It works, thanks a lot ! – Drak432 Aug 03 '21 at 13:53
  • Does this answer your question? [Where should I put – secan Aug 03 '21 at 13:56

1 Answers1

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>
G-Cyrillus
  • 94,270
  • 13
  • 95
  • 118