Toggle button : Javascript toggle doesn't works locally

Viewed 106

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 ?

1 Answers

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>

Related