user874737
user874737

Reputation: 533

Closing multiple popups one at a time

I have three popups that appear when the page loads, and only the first one is displayed while the rest is hidden. Each popup contains an image.

<div class="popup-container" tabindex="0">

<div class="popup-wrapper"> //1st popup
<img src="/popup/image-1.jpg" alt="photo">
</div>

<div class="popup-wrapper"> //2nd popup
<img src="/popup/image-2.jpg" alt="photo">
</div>

<div class="popup-wrapper"> //3rd popup
<img src="/popup/image-3.jpg" alt="photo">
</div>

</div>

The 2nd and 3rd popups have a display set to none via css.

.popup-wrapper:nth-child(n+2) {
display: none;
}

My question is how can I show the second popup after closing the first one, and so on from the second popup to third using ESC key.

So far here's my jquery:

$(".popup-container").on("keydown", function(e) {
if(e.which == 27) {
$(".popup-container .popup-wrapper").hide(); //closes the currently shown popup
}
});

Upvotes: 0

Views: 101

Answers (1)

epascarello
epascarello

Reputation: 207501

You can use next and show since they are siblings.

$(".popup-container").on("keydown", function(e) {
  if (e.which == 27) {
    $(".popup-container .popup-wrapper:visible")
      .hide()
      .next()
        .show(); 
  }
});
.popup-wrapper:nth-child(n+2) {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="popup-container" tabindex="0">

  <div class="popup-wrapper"> //1st popup
    <img src="/popup/image-1.jpg" alt="photo">
  </div>

  <div class="popup-wrapper"> //2nd popup
    <img src="/popup/image-2.jpg" alt="photo">
  </div>

  <div class="popup-wrapper"> //3rd popup
    <img src="/popup/image-3.jpg" alt="photo">
  </div>

</div>

Upvotes: 1

Related Questions