Mostafa Talebi
Mostafa Talebi

Reputation: 9173

jQuery event delegation and attachment issue

I have a set of three elements. And there are many coming elements after the page load by ajax when the user clicks on a certain element. I iterate over initial elements with each and attach an event to them like this:

tagSet.each(function(index, element){

   tagSet.eq(index).on("click",function(){alert("Alerted! Clicked")});
}

But with this approach those ajax-created elements would not be attached with an event. Thus I have to make a little bit of change to on() for it accommodate the ajax-created elements:

tagSet.each(function(index, element){

   $(document).on("click",tagSet.eq(index),function(){alert("Alerted! Clicked")});
}

It solve the problem of event attachment to those ajax-created elements but raises another issue. It attaches the event in a way that all of the elements of the page gets trigged with that specific event at once. I mean, since I have three elements, a click on one of them cause all three alert("Alerted!Clicke!) to trigger. What is the issue and the solution?

Upvotes: 0

Views: 35

Answers (1)

Brian Hadaway
Brian Hadaway

Reputation: 1893

Use event delegation to bind to all current and future items that match a query:

$(document).on("click", ".some-class-here", function(){
    alert("Alerted! Clicked")
});

Replace .some-class-here with a selector that matches your tagSet elements. Then remove your call to $.each.

Upvotes: 1

Related Questions