Home > Back-end >  Hiding Unhiding Div Properly using vanilla JavaScript
Hiding Unhiding Div Properly using vanilla JavaScript

Time:08-09

I Have a div which I display on button click which works fine but on the second button click this is not invoked what's wrong here

document.getElementById("btn1").addEventListener('onclick', myFunction());

function myFunction() {
  var x = document.getElementById("myDIV");
  if (x.style.display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
}
<button onclick='myFunction()'>Toggle</button>
<div id="myDIV" style="display: none;">
  <div  role="status">
    <h4 >Loading...</span>
  </div>
</div>

CodePudding user response:

Welcome. Into the snippet there are some little mistakes:

  1. The html for the button lacks of its own id that you are using in the js to get the element and to add the event listener to it;
  2. The javascript line you use to add the event uses onclick event, this doesn't work because with addEventListener, you have to use just the event without the on part that is needed if you use the inline version of the event, into the html. So basically will be used just click, not onclick;
  3. Adding the event listener don't use the ( ) part of the function that you are adding, that basically makes it execute immediately at the moment the event listener is added to the html element: use just its name so just myFunction;
  4. Also because we are adding the event listener by js we don't need to use the onclick='myFunction()' part into the html: we use one or the other no need to use both. Also the addEventListener way is usually the preferred way to go instead the inline version onclick='myFunction()'. In fact, the addEventListener way, keeps the html code cleaner and allows to add multiple events of the same type. But with the onclick='myFunction()' way you can only add one event inline.
  5. One more suggestion would be to use a separate css instead of inline style.

Now let's see the corrections in action:

document.getElementById("myBtn").addEventListener('click', myFunction);

function myFunction() {
  let divElStyle = document.getElementById("myDIV").style;
  if (divElStyle.display === "none") {
    divElStyle.display = "block";
  } else {
    divElStyle.display = "none";
  }
}
<button id="myBtn">Toggle</button>
<div id="myDIV"  role="status" style="display:none;" >
  <h4 >Loading...</span>
</div>

  • Related