-1

I have always had an issue in case when elements added to the DOM through AJAX don't seem to get the relevant jQuery.on() handlers attached to them. So I ended up with re-adding the events to them in the AJAX complete function.

But I always wondered if jQuery.on() should be attaching to them and if so then why isn't it?

shershen
  • 9,875
  • 11
  • 39
  • 60
Mat Kay
  • 508
  • 1
  • 11
  • 24
  • 1
    Just read more carefully `on()` documentation, that's clearly explained – A. Wolff Jul 18 '15 at 11:22
  • Read about delegated events. `on()` uses delegated events and will apply to any elements added to the DOM later provided you use the right selector. – Mitya Jul 18 '15 at 11:31

3 Answers3

1

There are different kinds of event bindings in jQuery.

The code below will attach click event only to the currently available DOM elements, and on removal or re-addition of the elements, the event will work no more

$(".myElement").on("click", function() {
    console.log("Clicked!");
})

The below method will attach click event to all the elements with the given selector for the whole lifecycle of the DOM, irrespective of addition and removal of the elements any number of times.

$(document).on("click", ".myElement", function() {
    console.log("Clicked!");
})
Kamran Ahmed
  • 7,661
  • 4
  • 30
  • 55
  • that worked thanks. Should I attach all my events the second way in future or is it more costly to do it that way? – Mat Kay Jul 18 '15 at 11:40
0

What version of jQuery you're using?

Previously, before 1.9 there was a jQuery.live() - API docs link to add event handlers to the elements that did't exist in the DOM yet. But since 1.7 jQuery.on() - API docs link works in the same fashion.

shershen
  • 9,875
  • 11
  • 39
  • 60
0

How you used on method? what is the version of jQuery that you using? instead of on, you can use delegate as well. here is more info about delegate

Mehdi Dehghani
  • 10,970
  • 6
  • 59
  • 64