Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problems with javascript event handler

I'm hoping this doesn't get marked as "duplicate", because I have reviewed several threads and followed the advice I found. I know I'm missing something simple, and need other eyes on this. I'm a newbie, so please bear with me. I am testing a simple button element that I have a click event handler on, but it is not working. It works inline with "onclick", but I am trying to avoid that. The simple html:

<div>
    <button id='handler'>Event</button>
</div>
<div id='stringText'>
    <h4>Some Description</h4>
    <p>
        Some more information
    </p>
</div>

And the javascript:

<script>
    document.getElementById("handler").addEventListener("click", display, true);
    function display() {

        if (document.getElementById("stringText").style.display === "block") {
            document.getElementById("stringText").style.display = "none";
        } else {
            document.getElementById("stringText").style.display = "block";
        }

    };

</script>

I have the css that initially sets the "stringText" display as "none". I appreciate any assistance.

like image 201
Pops Jones Avatar asked Mar 27 '18 02:03

Pops Jones


1 Answers

  • Probably your problem is related to the execution of that script while the document is being loaded.
  • Add this condition stringText.style.display === "" to show/hide the elements correctly.

An alternative is using the event DOMContentLoaded

document.addEventListener("DOMContentLoaded", function(event) {
  console.log("DOM fully loaded and parsed");
  document.getElementById("handler").addEventListener("click", display, true);

  function display() {
    var stringText = document.getElementById("stringText");
    if (stringText.style.display === "block" || stringText.style.display === "") {
      stringText.style.display = "none";
    } else {
      stringText.style.display = "block";
    }
  };
});
<div>
  <button id='handler'>Event</button>
</div>
<div id='stringText'>
  <h4>Some Description</h4>
  <p>
    Some more information
  </p>
</div>
like image 193
Ele Avatar answered Oct 31 '22 03:10

Ele