Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

158
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!