AoW
AoW

Reputation: 55

Jquery close popup

i'm trying to write jquery code, that will close simple popup. Here is example.

When i click on any image, popup is shown, but when i'm trying to close it, it doesn't work. I think it's becouse it's closing and showing again.

$(".li").click(function() {
  $(".popup", this).show();
});

$(".popup").click(function() {
  $(".popup").hide();
});
.popup {
  background-color: black;
  opacity: 0.8;
  height: 60%;
  width: 60%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="li">
  <img src="foo.jpg">
  <div class="popup" style="display: none;">POPUP</div>
</div>

<div class="li">
  <img src="foo.jpg">
  <div class="popup" style="display: none;">POPUP</div>
</div>

<div class="li">
  <img src="foo.jpg">
  <div class="popup" style="display: none;">POPUP</div>
</div>

<div class="li">
  <img src="foo.jpg">
  <div class="popup" style="display: none;">POPUP</div>
</div>

Upvotes: 1

Views: 59

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337560

Your issue is that the .popup is within the li element, so when you click the .popup it gets hidden, but the click handler also immediately runs on the li to show it again.

To fix this, call stopPropagation() on the event passed to the .popup click handler, like this:

$(".li").click(function() {
  $(".popup", this).show();
});

$(".popup").click(function(e) { // receive the event parameter here
  e.stopPropagation(); // and stop the event bubbling up the DOM here
  $(".popup").hide();
});
.popup {
  background-color: black;
  opacity: 0.8;
  height: 60%;
  width: 60%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="li">
  <img src="foo.jpg">
  <div class="popup" style="display: none;">POPUP</div>
</div>

<div class="li">
  <img src="foo.jpg">
  <div class="popup" style="display: none;">POPUP</div>
</div>

<div class="li">
  <img src="foo.jpg">
  <div class="popup" style="display: none;">POPUP</div>
</div>

<div class="li">
  <img src="foo.jpg">
  <div class="popup" style="display: none;">POPUP</div>
</div>

Also note that your current code will close all open .popup elements. You may want to change $('.popup').hide() to $(this).hide() if you only want to close the clicked popup.

Upvotes: 1

Related Questions