Reputation: 42
Here is the fiddle. Ignore the styling, that's not important.
Basically I needed to open the Fancybox with two links present, but I only want one gallery image. I figured that out easily enough. When the thumbnail is clicked it triggers the li anchor.
To keep the galleries separate I did unique classes for each ol.
The problem I have run into is I will be repeating myself. I attempted to do a loop (commented out), but the logic is beyond my grasp.
What is the best way to attach a new click handler (I need to add 8 more) without repeating myself in my current fashion? I've also tried a function with a couple parameters, but I had trouble with the e.preventDefault()
.
I greatly appreciate any guidance, thanks!
Upvotes: 0
Views: 49
Reputation: 1095
This looks like a great use case to use jQuery's on()
method. on()
is a method that will allow you to establish a handler on an outer container that can listen to its children for click events. So, for example: if you specified a class of .js-listen
on your lists, you could call on()
like this:
$('.js-listen').on('click', 'other-selector', function(e){
// function logic with either $(this) or e.target goes here
}
This block would essentially look for all elements with .js-listen
and then when something inside the element with the .js-listen
class is clicked, the event will bubble up through the DOM and the event will be handled according to the element that was clicked. The second parameter I have 'other-selector'
can be a class name, element, or ID. so you could essentially put something like img
there and it would fire the event if the child element clicked was an <img>
tag.
This prevents you from attaching a handler a million times, and one of the benefits of on()
is that if elements are dynamically added to the container with the handler, you don't have to worry about attaching handlers to those elements, because again, they bubble up!
Hope this helps!
Upvotes: 1