6

I know of and research multiple ways to bind events .on(), .live(), .click(), etc. I know .live() is deprecated in 1.9+. The problem I'm encountering is binding dynamic DOM elements to events.

I have a div that contains links and is paginated. The links are dynamically loaded with AJAX. I want to overwrite binded events for these links so I used .unbind() and tried .on(). The problem is that these dynamically loaded links are not binded. I guess that's because the selector $('#id_of_links') is cached with the previous set of links.

QUESTION: Is it possible to bind all elements that are loaded on the page, at any point in time, without having to set a callback when the user clicks next page on the links?

Eric Kim
  • 256
  • 4
  • 9

2 Answers2

15

for dynamically added elements, you must bind the function to one of it's parents

$('#PARENT').on('click', '#DYNAMICALLY_ADDED_CHILD', function(){ CODE HERE });

Parent should already exist in the DOM tree...

More info on: http://api.jquery.com/on/

YomY
  • 603
  • 6
  • 16
  • Thanks. Is there a way to dynamically unbind events? – Eric Kim Jun 03 '13 at 14:26
  • 1
    There is the .off() method that is the opposite of .on(), You can check http://api.jquery.com/off/ I haven't tried it yet, but I suppose that it would go something like $('#PARENT').off('click', '#DYNAMICALLY_ADDED_CHILD', null); – YomY Jun 03 '13 at 17:08
-2

You cannot bind all elements, even those not loaded in the page yet, without having a callback method/function or a function that would loop in and keep checking if the elements with a specific attribute or characteristic would have the proper function binded to it, which would probably cause a memory leak over time.

Jeff Noel
  • 7,500
  • 4
  • 40
  • 66
  • 1
    You can delegate the events to a parent (see @yomy answer). In that way, only one element will have the event associated with it, and it will be fired only when it's specific children (mentionnend in the on method) will fire it. This is the opposite of a memory leak ;) – Cyril N. Jun 03 '13 at 13:58
  • @CyrilN.Alright, thanks for showing it up. I need to read more on the features of the `.on()` method! – Jeff Noel Jun 03 '13 at 14:50
  • 1
    You should, it's very interesting and it will greatly help you in the future :) – Cyril N. Jun 04 '13 at 07:23