0

I've made a light box with jQuery and can get the modal window to close if I select to use the body tag as the target to click and close. However, if I change it to my .closeBtn, nothing will happen. I've tried several variations of what I know to get it to work, but no luck. Any information would be most appreciated.

Cheers

// USING JQUERY CDN

$( document ).ready(function() {
       $('.lightbox-trigger').click(function(e) {
        e.preventDefault();
        let image_href = $(this).attr("href");
        if ($('#lightbox').length > 0) { 
            $('#content').html('<img src="' + image_href + '" />');
            $('#lightbox').show('fast');
        } else { 
            let lightbox = 
            '<div id="lightbox">' +
                '<p class="closeBtn">&times;</p>' +
                '<div id="content">' + 
              '<img class="lightbox-img" src="' + image_href +'" />' +
                '</div>' +  
                '<a class="prev arrowBTN" aria-label="previous page">&#10094;</a>' + 
                '<a class="next arrowBTN" aria-label="next page">&#10095;</a>' +
            '</div>';
            $('body').append(lightbox);
        }
         $('.gallery-container').addClass('lightbox-active');
    });
     
    $('.closeBtn').on('click', '#lightbox', function() { 
        $('#lightbox').hide();
      $('.gallery-container').removeClass('lightbox-active');
    });
});
// END OF FUNCTION
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  background-color: black;
}

body {
  color: white;
  font-family: 'Montserrat';
}

/* ///////////////////// NAVBAR //////////////////////// */
.navbar-style {
  box-shadow: 0 4px 2px -2px #333;
}

.nav-logo {
  width: 10%;
}

.nav-custom img {
  width: 64px;
}

.icon-bar {
  background: white;
}

/* ///////////////////// NAVBAR //////////////////////// */

/* ///////////////////// MAIN AREA //////////////////////// */

.slogan h1 {
  font-weight: 200;
  font-size: 1.2rem;
  margin-top: 2rem;
  margin-left: 2rem;
}

.background-img img {
  width: 80%;
}

.button {
  margin-top: 2rem;
  margin-left: 2rem;
  background-color: black;
}

.blurb {
  font-family: 'League Script', cursive;
  font-weight: 100;
  margin-top: 2rem;
  margin-left: 2rem;
}

/* ///////////////////// FRONT GALLERY //////////////////////// */



.gallery-container {
  display: flex;
  justify-content: center;
  border: solid 1px white;
  margin: 0, auto;
}

.flex-column {
  justify-content: space-between; /* have images appear as a four sided block */
  max-width: 250px;
}

/* ---------- LIGHTBOX ---------- */

#lightbox {
  position: fixed; 
/*  ^keeps lightbox window in the current viewport  */
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  text-align: center;
  background: rgba(0,0,0,.7);
  
}

/* LIGHTBOX CLOSE BUTTON */
#lightbox .closeBtn {
  text-align: right;
  margin-right: 20px;
  font-size: 3rem;
}

.closeBtn {
  cursor: pointer;
}

/* LIGHTBOX IMAGE */
#lightbox img {
  box-shadow: 0 0 25px #111;
  max-width: 300px;
}

#content {
  display: flex;
  justify-content: center;
}

#content img{
  position: fixed;
  top: 0;
  margin-top: 4rem;
  width: 100%;
}

/* BLUR BACKGROUND WHEN LIGHTBOX IS ACTIVE */
.lightbox-active {
  filter: blur(5px);
}


/* LIGHTBOX ARROWS */
.arrowBTN {
  position: absolute;
  text-decoration: none;
  color: white;
  font-size: 2rem;
  text-align: center;
  margin-top: 25%;
  transform: translateY(-25%);
  width: 3rem;
  height: 3rem;
  border-radius: 50%;
  background-color: rgba(255,255,255,0.5);
}

.prev {
  left: 0;
  margin-left: 1rem;
}

.next {
  right: 0;
  margin-right: 1rem;
}

#lightbox a {
  text-decoration: none;
   color: white;
}

#lightbox a:hover {
   background-color: rgba(255,255,255, 0.2);
}




















@media screen and (min-width: 1650px) {
  .flex-column {
    display: flex;
    justify-content: space-evenly;
  }
}

img {
  margin: 5px;
}



/* ///////////////////////////////////// */
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section id="front-gallery">
      <div class="container-fluid gallery-container">
        <div class="d-flex flex-row">
          
<!--   ////////  1st COLUMN   ////////    -->    
          <div class="d-flex flex-column">
<!--      FIRST IMAGE        -->
            <a style="display:contents" href="https://cdn.pixabay.com/photo/2017/04/05/17/45/girl-2205813_1280.jpg" class="lightbox-trigger">
            <img src="https://cdn.pixabay.com/photo/2017/04/05/17/45/girl-2205813_1280.jpg" alt="woman black and white photo" class="img-fluid">
            </a>
            
<!--      SECOND IMAGE        -->
            <a style="display:contents" href="https://cdn.pixabay.com/photo/2014/10/13/18/10/woman-487090_1280.jpg" class="lightbox-trigger">
            <img src="https://cdn.pixabay.com/photo/2014/10/13/18/10/woman-487090_1280.jpg" alt="dog" class="img-fluid">
            </a>
          </div>
          
<!--   ////////  2nd COLUMN   ////////    -->       
    <div class="d-flex flex-column">
<!--      THIRD IMAGE        -->
       <a style="display:contents" href="https://cdn.pixabay.com/photo/2016/11/29/13/00/black-1869685_1280.jpg" class="lightbox-trigger">
            <img src="https://cdn.pixabay.com/photo/2016/11/29/13/00/black-1869685_1280.jpg" alt="woman color photo" class="img-fluid">
      </a>
<!--      FOURTH IMAGE        -->   
             <a style="display:contents" href="https://cdn.pixabay.com/photo/2015/03/04/19/42/woman-659352_1280.jpg" class="lightbox-trigger">
            <img src="https://cdn.pixabay.com/photo/2015/03/04/19/42/woman-659352_1280.jpg" alt="woman with tattoos" class="img-fluid">
      </a>
            </div>
          
 <!--   ////////  3rd COLUMN   ////////    -->     
  <div class="d-flex flex-column">
<!--      FIFTH IMAGE        -->  
                 <a style="display:contents" href="https://cdn.pixabay.com/photo/2015/07/02/10/11/person-828630_1280.jpg" class="lightbox-trigger">
            <img src="https://cdn.pixabay.com/photo/2015/07/02/10/11/person-828630_1280.jpg" alt="outline of man photo" class="img-fluid">
    </a>
    
<!--      SIXTH IMAGE        -->   
     <a style="display:contents" href="https://cdn.pixabay.com/photo/2017/05/27/17/52/model-2349037_1280.jpg" class="lightbox-trigger">
            <img src="https://cdn.pixabay.com/photo/2017/05/27/17/52/model-2349037_1280.jpg" alt="woman under water" class="img-fluid">
    </a>
            </div>
          
<!--   ////////  4th COLUMN   ////////    -->              
  <div class="d-flex flex-column">
 <!--      SEVENTH IMAGE        -->  
         <a style="display:contents" href="https://cdn.pixabay.com/photo/2016/02/11/19/14/couple-1194312_1280.jpg" class="lightbox-trigger">
            <img src="https://cdn.pixabay.com/photo/2016/02/11/19/14/couple-1194312_1280.jpg" alt="couple" class="img-fluid">
    </a>

<!--      EIGHTH IMAGE        -->  
             <a style="display:contents" href="https://cdn.pixabay.com/photo/2017/11/03/10/34/studio-2913936_1280.jpg" class="lightbox-trigger">
            <img src="https://cdn.pixabay.com/photo/2017/11/03/10/34/studio-2913936_1280.jpg" alt="woman smiling" class="img-fluid">
               </a>
            </div>
          
 <!--   ////////  5th COLUMN   ////////    -->             
  <div class="d-flex flex-column">
<!--      NINTH IMAGE        -->    
             <a style="display:contents" href="https://cdn.pixabay.com/photo/2016/11/14/04/08/selfie-1822563_1280.jpg" class="lightbox-trigger">
              <img src="https://cdn.pixabay.com/photo/2016/11/14/04/08/selfie-1822563_1280.jpg" alt="kids taking selfie in field" class="img-fluid">
               </a>
    
<!--      TENTH IMAGE        -->  
                        <a style="display:contents" href="https://cdn.pixabay.com/photo/2021/04/02/12/01/woman-6144753_1280.jpg" class="lightbox-trigger">
              <img src="https://cdn.pixabay.com/photo/2021/04/02/12/01/woman-6144753_1280.jpg" alt="woman with eye makeup" class="img-fluid">
                          </a>
            </div>
          
 <!--   ////////  6th COLUMN   ////////    -->             
  <div class="d-flex flex-column">
<!--      ELEVENTH IMAGE        -->   
             <a style="display:contents" href="https://cdn.pixabay.com/photo/2016/10/27/03/43/radio-1773304_1280.jpg" class="lightbox-trigger">
              <img src="https://cdn.pixabay.com/photo/2016/10/27/03/43/radio-1773304_1280.jpg" alt="vintage radio" class="img-fluid">
               </a>
    
<!--      TWELFTH IMAGE        -->    
                        <a style="display:contents" href="https://cdn.pixabay.com/photo/2015/06/24/01/16/photographer-819365_1280.jpg" class="lightbox-trigger">
              <img src="https://cdn.pixabay.com/photo/2015/06/24/01/16/photographer-819365_1280.jpg" alt="outdoor photographer" class="img-fluid">
                          </a>
            </div>
          
 <!--   ////////  7th COLUMN   ////////    -->             
  <div class="d-flex flex-column">
    
<!--      THITEENTH IMAGE        -->  
             <a style="display:contents" href="https://cdn.pixabay.com/photo/2015/04/12/18/05/man-719228_1280.jpg" class="lightbox-trigger">
              <img src="https://cdn.pixabay.com/photo/2015/04/12/18/05/man-719228_1280.jpg" alt="man thinking" class="img-fluid">
               </a>
    
<!--      FOURTEENTH IMAGE        -->   
                        <a style="display:contents" href="https://cdn.pixabay.com/photo/2016/11/29/01/34/man-1866572_1280.jpg" class="lightbox-trigger">
              <img src="https://cdn.pixabay.com/photo/2016/11/29/01/34/man-1866572_1280.jpg" alt="man with jacket" class="img-fluid">
                          </a>
            </div>
          
          
          </div> <!-- END FLEX ROW -->
      </div>  <!-- END CONTAINER -->
    </section>



<!-- ////////////////////////////// -->
<!-- <div id="lightbox2">
  <p class="closeBtn2">&times;</p>
  <div id="content2">
    <img class="lightbox-img2" src="' + image_href +'" />
    <img class="lightbox-img2" src="https://cdn.pixabay.com/photo/2016/11/14/04/08/selfie-1822563_1280.jpg" />
  </div>
 
  <a class="prev2 arrowBTN2" aria-label="previous page">&#10094;</a>
  <a class="next2 arrowBTN2" aria-label="next page">&#10095;</a>
</div> -->
KurtReyn
  • 23
  • 5
  • Does this answer your question? [Event binding on dynamically created elements?](https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – freedomn-m Oct 21 '21 at 15:24
  • jQuery events only apply to elements that exist at the time the event is added. Just before your line `$('.closeBtn').on('click'` add `console.log($('.closeBtn').length)` - it will likely be zero and if it's not it certainly won't reference the .closeBtn that you add later. – freedomn-m Oct 21 '21 at 15:26
  • Your use of `$('.closeBtn').on('click', '#lightbox',` is also incorrect as the call is `$("existing_selector").on("click", "selector_for_child_of_existing_selector"` - and `#lightbox` is not a child of `.closeBtn` - you *probably* want `$(document).on("click", "#lightbox .closeBtn", function...` to ensure it's only the button that's in the lightbox that's getting clicked. – freedomn-m Oct 21 '21 at 15:28
  • appending a new ` – Mark Schultheiss Oct 21 '21 at 16:09
  • @freedomn-m and Mark Schultheiss: thank you both for the information. I suspected it may not be working because being loaded dynamically, but I wasn't certain. Looks like I'll need to make a static div as Mark suggested. – KurtReyn Oct 21 '21 at 16:37
  • 1
    Static div will work fine if you only ever show one (as an aside, update your content before showing it - see this far too often: `$(div).show().html(new_html)` and it pops up with the old content - terrible UX - even happens with Chrome tooltips!). Otherwise, there's no reason not to use event delegation. – freedomn-m Oct 21 '21 at 16:39

2 Answers2

2

This is not fully functional since you did not specify how you implemented the lightbox functionality (a plugin?) but that is not the question, the question is how to implement the click - here I show a static div for a lightbox inside #first-container however, if you wished to insert one dynamically that could also be done.

I showed how to add a second one as well. I just cloned the first one with all the attached event handlers and appended it to the second container, then triggered an image that pointed to with with a data attribute- key here is the click event handler works for the close button since it is attached to the lightbox-container class

$(function() {
  $('.lightbox-trigger').on('click', function(event) {
    event.preventDefault();
    let imageHref = $(this).attr("href");
    let targetBox = $(this).data('targetlightbox');
    //console.log("tb:",targetBox);
    //target or default selector set for targetBox
    targetBox = targetBox ? targetBox : '.lightbox-thing:first';
    console.log("tb:",targetBox);
    let lightBox = $(targetBox);
    lightBox.find('.lightbox-content').find('.lightbox-img').attr('src', imageHref);
    lightBox.show('fast');
    $('.gallery-container').addClass('lightbox-active');
  });
  $('.lightbox-container').on('click', '.closeBtn', function(event) {
    $(event.delegateTarget).find('.lightbox-thing').hide(); // the lightbox
    $('.gallery-container.lightbox-active').removeClass('lightbox-active');
  });

  /* add a second lightbox - by cloning first one */
  /* rather than embed in script, I just cloned the prior one here but it IS dynamic */
  let newBox = $('.lightbox-container:first').find('.lightbox-thing').clone(true);
  newBox.addClass('new-lightbox');
  // console.log("nb:",newBox.length);
  // console.log(newBox.attr('class'));
  $('#second-container').append(newBox);
  // console.log("appended:",$(".lightbox-thing").last().attr('class'), $('.lightbox-trigger').last().data('xx'));
  $('.lightbox-trigger').last().trigger('click');//trigger click on last which has a target
 // $('.lightbox-trigger').eq(2).trigger('click');
});
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  background-color: black;
}

body {
  color: white;
  font-family: 'Montserrat';
}

.icon-bar {
  background: white;
}

.slogan h1 {
  font-weight: 200;
  font-size: 1.2rem;
  margin-top: 2rem;
  margin-left: 2rem;
}

.background-img img {
  width: 80%;
}

.button {
  margin-top: 2rem;
  margin-left: 2rem;
  background-color: black;
}

.blurb {
  font-family: 'League Script', cursive;
  font-weight: 100;
  margin-top: 2rem;
  margin-left: 2rem;
}

.gallery-container {
  display: flex;
  justify-content: center;
  border: solid 1px white;
  margin: 0, auto;
}

.flex-column {
  justify-content: space-between;
  max-width: 250px;
}

.lightbox-container {
  position: fixed;
  /*  ^keeps lightbox window in the current viewport  */
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  text-align: center;
  background: rgba(0, 0, 0, .7);
  border: solid yellow 1px;
}

.lightbox-container .closeBtn {
  text-align: right;
  margin-right: 20px;
  font-size: 3rem;
}

.closeBtn {
  cursor: pointer;
}

.lightbox-container img {
  box-shadow: 0 0 25px #111;
  max-width: 300px;
}

.lightbox-content {
  display: flex;
  justify-content: center;
}

.lightbox-container .lightbox-content img {
  position: fixed;
  top: 0;
  margin-top: 4rem;
  width: 100%;
}

.lightbox-active {
  filter: blur(5px);
}

.arrowBTN {
  position: absolute;
  text-decoration: none;
  color: white;
  font-size: 2rem;
  text-align: center;
  margin-top: 25%;
  transform: translateY(-25%);
  width: 3rem;
  height: 3rem;
  border-radius: 50%;
  background-color: rgba(255, 255, 255, 0.5);
}

.prev {
  left: 0;
  margin-left: 1rem;
}

.next {
  right: 0;
  margin-right: 1rem;
}

.lightbox-container a {
  text-decoration: none;
  color: white;
}

.lightbox-container a:hover {
  background-color: rgba(255, 255, 255, 0.2);
}

@media screen and (min-width: 1650px) {
  .flex-column {
    display: flex;
    justify-content: space-evenly;
  }
}

img {
  margin: 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<section id="front-gallery">
  <div class="container-fluid gallery-container">
    <div class="d-flex flex-row">
      <div class="d-flex flex-column">
        <a style="display:contents" href="https://cdn.pixabay.com/photo/2017/04/05/17/45/girl-2205813_1280.jpg" class="lightbox-trigger">
          <img src="https://cdn.pixabay.com/photo/2017/04/05/17/45/girl-2205813_1280.jpg" alt="woman black and white photo" class="img-fluid">
        </a>
        <a style="display:contents" href="https://cdn.pixabay.com/photo/2014/10/13/18/10/woman-487090_1280.jpg" class="lightbox-trigger">
          <img src="https://cdn.pixabay.com/photo/2014/10/13/18/10/woman-487090_1280.jpg" alt="dog" class="img-fluid">
        </a>
      </div>
      <div class="d-flex flex-column">
        <a style="display:contents" href="https://cdn.pixabay.com/photo/2016/11/29/13/00/black-1869685_1280.jpg" class="lightbox-trigger">
          <img src="https://cdn.pixabay.com/photo/2016/11/29/13/00/black-1869685_1280.jpg" alt="woman color photo" class="img-fluid">
        </a>
        <a style="display:contents" href="https://cdn.pixabay.com/photo/2015/03/04/19/42/woman-659352_1280.jpg" class="lightbox-trigger">
          <img src="https://cdn.pixabay.com/photo/2015/03/04/19/42/woman-659352_1280.jpg" alt="woman with tattoos" class="img-fluid">
        </a>
      </div>
      <div class="d-flex flex-column">
        <a style="display:contents" href="https://cdn.pixabay.com/photo/2015/07/02/10/11/person-828630_1280.jpg" class="lightbox-trigger">
          <img src="https://cdn.pixabay.com/photo/2015/07/02/10/11/person-828630_1280.jpg" alt="outline of man photo" class="img-fluid">
        </a>
        <a style="display:contents" href="https://cdn.pixabay.com/photo/2017/05/27/17/52/model-2349037_1280.jpg" class="lightbox-trigger">
          <img src="https://cdn.pixabay.com/photo/2017/05/27/17/52/model-2349037_1280.jpg" alt="woman under water" class="img-fluid">
        </a>
      </div>
      <div class="d-flex flex-column">
        <a style="display:contents" href="https://cdn.pixabay.com/photo/2016/02/11/19/14/couple-1194312_1280.jpg" class="lightbox-trigger">
          <img src="https://cdn.pixabay.com/photo/2016/02/11/19/14/couple-1194312_1280.jpg" alt="couple" class="img-fluid">
        </a>
        <a style="display:contents" href="https://cdn.pixabay.com/photo/2017/11/03/10/34/studio-2913936_1280.jpg" class="lightbox-trigger">
          <img src="https://cdn.pixabay.com/photo/2017/11/03/10/34/studio-2913936_1280.jpg" alt="woman smiling" class="img-fluid">
        </a>
      </div>
      <div class="d-flex flex-column">
        <a style="display:contents" href="https://cdn.pixabay.com/photo/2016/11/14/04/08/selfie-1822563_1280.jpg" class="lightbox-trigger">
          <img src="https://cdn.pixabay.com/photo/2016/11/14/04/08/selfie-1822563_1280.jpg" alt="kids taking selfie in field" class="img-fluid">
        </a>
        <a style="display:contents" href="https://cdn.pixabay.com/photo/2021/04/02/12/01/woman-6144753_1280.jpg" class="lightbox-trigger">
          <img src="https://cdn.pixabay.com/photo/2021/04/02/12/01/woman-6144753_1280.jpg" alt="woman with eye makeup" class="img-fluid">
        </a>
      </div>
      <div class="d-flex flex-column">
        <a style="display:contents" href="https://cdn.pixabay.com/photo/2016/10/27/03/43/radio-1773304_1280.jpg" class="lightbox-trigger" data-targetlightbox=".new-lightbox">
          <img src="https://cdn.pixabay.com/photo/2016/10/27/03/43/radio-1773304_1280.jpg" alt="vintage radio" class="img-fluid">
        </a>
        <a style="display:contents" href="https://cdn.pixabay.com/photo/2015/06/24/01/16/photographer-819365_1280.jpg" class="lightbox-trigger">
          <img src="https://cdn.pixabay.com/photo/2015/06/24/01/16/photographer-819365_1280.jpg" alt="outdoor photographer" class="img-fluid">
        </a>
      </div>
      <div class="d-flex flex-column">
        <a style="display:contents" href="https://cdn.pixabay.com/photo/2015/04/12/18/05/man-719228_1280.jpg" class="lightbox-trigger" data-targetlightbox=".new-lightbox">
          <img src="https://cdn.pixabay.com/photo/2015/04/12/18/05/man-719228_1280.jpg" alt="man thinking" class="img-fluid">
        </a>
        <a style="display:contents" href="https://cdn.pixabay.com/photo/2016/11/29/01/34/man-1866572_1280.jpg" class="lightbox-trigger" data-targetlightbox=".new-lightbox">
          <img src="https://cdn.pixabay.com/photo/2016/11/29/01/34/man-1866572_1280.jpg" alt="man with jacket" class="img-fluid">
        </a>
      </div>
    </div>
  </div>
</section>
<div id="first-container" class="lightbox-container">
  <div class="lightbox-thing">
    <p class="closeBtn">&times;</p>
    <div class="lightbox-content">
      <img class="lightbox-img" src="#" />
    </div>
    <a class="prev arrowBTN" aria-label="previous page">&#10094;</a>
    <a class="next arrowBTN" aria-label="next page">&#10095;</a>
  </div>
</div>
<div id="second-container" class="lightbox-container">
</div>
Mark Schultheiss
  • 32,614
  • 12
  • 69
  • 100
  • Thank you so much for taking the time to help me with this! Your efforts are immensely appreciated. So, I took your advice and made the Lightbox static. Now, I'm trying to find a way to do a few things. 1st: when a user clicks an image in the gallery, the image that is clicked on pops up in the Lightbox. 2nd once the Lightbox is active, the user can then use the left and right arrows to navigate to the next/prev image in sequence. Not having any luck so far. I've made a Codepen if you would like to see what I've got. https://codepen.io/kurt-reynolds/pen/yLoVmoy thank you again!!! – KurtReyn Oct 22 '21 at 20:57
0

This is because, you are trying to click a button that is generated dynamically. Try this,

$('body').on('click', '#lightbox .closeBtn', function() { 
        $('#lightbox').hide();
      $('.gallery-container').removeClass('lightbox-active');
    });
Jagadheesh
  • 49
  • 6
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Oct 21 '21 at 16:33
  • Thank you for the reply. Yes, I was able to get it to work with the body tag. It seems thought that I will need to make a static div if I want to use a class selector for my event handler. – KurtReyn Oct 21 '21 at 16:39