0
votes

I have created a custom lightbox with the following HTML:

<a href="#" class="lightbox">
    <img src="thumbnail.jpg" />
    <div class="box">
        <img class="boximage" src="full-image.jpg" />
        <p>Caption</p>
        <div class="close"><p>x</p></div>
    </div>
</a>

The following JavaScript opens the correct individual full .boximage class image when that individual thumbnail with .lightbox class is clicked on.

$('.lightbox').click(function(){
    $(this).find('.box, .boximage').css('display', 'block');
}); 

Previously I had some JavaScript which works to close the lightbox when you click on the close x.

$('.close').click(function(){
    $('.box, .boximage').css('display', 'none');
});

But I can't seem to get the close lightbox to work.

How do I make the close functionality work?

2
What happens when you try to close it?fstanis

2 Answers

1
votes

Use stopPropagation which prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.

$('.close').click(function(e){
   e.stopPropagation();
   $('.box, .boximage').css('display', 'none');
});

As you're binding click event in lightbox and clicking on close button applies to lightbox to be clicked also. So, you need to prevent bubbling up the tree.

0
votes

@BhojendraNepal has correctly pointed out that the key is to use event.stopPropagation(). In addition to that, if you need to have multiple such elements on a page, you want to keep the context of the click as follows:

$('.close').click(function(e){
    e.stopPropagation();
    $(this).closest('.box').css('display', 'none');
});

$('.lightbox').click(function(){
    $(this).find('.box, .boximage').css('display', 'block');
}); 
$('.close').click(function(e){
    e.stopPropagation();
    $(this).closest('.box').css('display', 'none');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
1. <a href="#" class="lightbox">
  <img src="thumbnail.jpg">
  <div class="box">
    <img class="boximage" src="full-image.jpg"/>
    <p>Caption</p>
    <div class="close">
      <p>x</p>
    </div>
  </div>
</a>
<br>2. 
<a href="#" class="lightbox">
  <img src="thumbnail.jpg">
  <div class="box">
    <img class="boximage" src="full-image.jpg"/>
    <p>Caption 2</p>
    <div class="close">
      <p>x</p>
    </div>
  </div>
</a>
<br>3. 
<a href="#" class="lightbox">
  <img src="thumbnail.jpg">
  <div class="box">
    <img class="boximage" src="full-image.jpg"/>
    <p>Caption 3</p>
    <div class="close">
      <p>x</p>
    </div>
  </div>
</a>