TRS7
TRS7

Reputation: 149

Trying to add a click event to individual elements but want them to execute one at a time

I have three div elements on a page and when each one is clicked they are supposed to disappear one at a time. Right now when I click one div element, they all disappear as a group. How do I make them disappear one at a time?

HTML

<div id=parentlist>
<div id="alert">
  <span class="closebtn">&times;</span> 
  <strong>Error!</strong>
</div>

<div id="alert2">
    <span class="closebtn">&times;</span> 
    <strong>Success!</strong>
  </div>



<div id="alert3">
   <span class="closebtn">&times;</span> 
    <strong>Warning!</strong>
  </div>

  </div>

JAVASCRIPT

document.addEventListener("click", function(){

    document.getElementById('alert').style.display = 'none';
    document.getElementById('alert2').style.display = 'none';
    document.getElementById('alert3').style.display = 'none';




});

Upvotes: 0

Views: 116

Answers (2)

user7148391
user7148391

Reputation:

You can try using timeout like this

document.addEventListener("click", function() {
  document.getElementById('alert').style.display = 'none';
  setTimeout(() => {
    document.getElementById('alert2').style.display = 'none';
    setTimeout(() => {
      document.getElementById('alert3').style.display = 'none';
    }, 500);
  }, 500);
});
<div id=parentlist>
  <div id="alert">
    <span class="closebtn">&times;</span>
    <strong>Error!</strong>
  </div>

  <div id="alert2">
    <span class="closebtn">&times;</span>
    <strong>Success!</strong>
  </div>
  <div id="alert3">
    <span class="closebtn">&times;</span>
    <strong>Warning!</strong>
  </div>
</div>

Upvotes: 1

user9090230
user9090230

Reputation:

First create an Array and then add an event listener to every element in the array using Array.forEach method of ES6.

The Code:

window.onload = function() {
  var divs = Array.from(document.querySelectorAll('.alerts'));
  divs.forEach(div => div.addEventListener('click', function() {
    div.style.display = 'none';
  }));
}
<div id=parentlist>
  <div id="alert" class='alerts'>
    <span class="closebtn">&times;</span> 
    <strong>Error!</strong>
  </div>

  <div id="alert2" class='alerts'>
    <span class="closebtn">&times;</span> 
    <strong>Success!</strong>
  </div>
  
  <div id="alert3" class='alerts'>
    <span class="closebtn">&times;</span> 
    <strong>Warning!</strong>
  </div>
</div>

Upvotes: 1

Related Questions