0

This should be simple, but I'm cracking my brain with the syntax.

I have a simple lightbox function that works perfectly with images that are already there at runtime. But I have a hidden div that loads content from another script - sometimes, it also includes images that I'd like to lightbox.

I know that I need to add on() here, but I'm screwing up the syntax.

Here is the working function layout:

$('.lightbox_trigger').click(function(e) {

//function body here

});//end function

This should be a simple fix, but when I wrap this in on(), I seem to be screwing it up. I'd love a quick suggestion. Thanks!

osuddeth
  • 152
  • 9
  • `$(x).click(f)` = `$(x).on("click", f)` for *event delegation* (that you want here) -> `$(document).on("click", x, f)` – freedomn-m Apr 19 '23 at 05:01

1 Answers1

1

Your jQuery selector .lightbox_trigger will attach the click event on every element with that class that is present when this line is run. However, if you add elements to your html dynamically after that code has already run. Those new elements will not have the event listener attached.

There are multiple ways to fix this, but you could attach the event listener to an element that is present and have it listen to that event on a child. For example:

$(document).on('click', '.lightbox_trigger', function () {
   console.log('clicked!!');
});

Now the event listener will also work on elements you add to the DOM later.

  • Thanks. I understand *why* it doesn't work, I was just struggling with the syntax. Let me go test it, I appreciate the help. Edit - bam, that works perfectly! Many thanks. – osuddeth Apr 19 '23 at 01:40
  • Yeah, I just wanted to explain why it works instead of just giving you some code. I always like to see some context. Good to hear that you fixed it! – Rob Meijerink Apr 19 '23 at 14:09
  • I absolutely do appreciate you explaining the "why". Even though I understood in this case, there are frequently aspects I haven't considered. Thanks again! – osuddeth Apr 19 '23 at 17:15