Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to register event on elements that don't yet exist?

Tags:

jquery

I am trying to register a event on elements like this:

$(document).ready(function() {
   $('.classname').change(function(){
       alert ('This line is never triggered');
   });
});

But the problem is that .classname elements are later loaded into the dom by ajax. So, how do I correctly register an event in this case? Is it possible to do it only once (I mean, not every time the new element appears?)

like image 682
Dziamid Avatar asked Jul 05 '11 12:07

Dziamid


People also ask

What method can you use to bind an event to an element?

jQuery bind() Method The bind() method attaches one or more event handlers for selected elements, and specifies a function to run when the event occurs.

How to add event dynamically in js?

To attach event handlers to the dynamically created button, we need to select the button with a class of btn and add an event listener of click . We're saying that onclick of the button, the p tag with a class of moreInfo should display block .


2 Answers

You must use on() as live() is deprecated:

$(document).ready(function() {
   $( document ).on('change', '.classname', function(){
       alert ('This line is never triggered');
   });
});
like image 140
Nicola Peluchetti Avatar answered Nov 15 '22 05:11

Nicola Peluchetti


Further to the answers suggesting that you use live(), it's also possible to use delegate(), for example:

$('form').delegate('.classname', 'change', function(){
    alert("This will alert when the newly-added element registers a 'change' event.");
});

For delegate the element to assign the selector (.classname') to, in this case the $('form') must exist in the DOM at the time of assignment.


Edited to note that the following section (following the next 'edited' until the 'Reference') is wrong:

JS Fiddle demo.

Calling stopPropagation() on an element between the element selected by the delegate() selector and the target to which the event is delegate()-d does somewhat predictably (though I hadn't realised this before) prevent the delegation from occurring.

Edited in response to question, in comments, from OP:

Hey, just noticed, that if any parent's event handler calls stopPropagation, then live event would stop! Is this correct?

Not according to the jQueryAPI (the entry is linked-to below):

...events handled by .delegate() will always propagate to the element to which they are delegated...

I've not tried/verified this as yet, but it seems that even if an element that sits between the target element ($('.classname')) and the delegate()-d element ($('form')) calls stopPropagation() it shouldn't have an adverse effect on the delegate().

Reference:

  • delegate().
like image 40
David Thomas Avatar answered Nov 15 '22 07:11

David Thomas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!