OnLoad of the new element, delegate / on?

I am trying to run a function on an element ( .this_button ) that loads dynamically. Im using the following code:

 $(function(){ $("body").on("load", ".this_button", function() { console.log("its been loaded"); }); }); 

I tried delegate , but it says that it is deprecated in favor of on . Some items can be pressed, say, after a document has been loaded for 10 minutes. How can he constantly check if the .this_button element .this_button entered the body?

Does anyone know why this is not working?

+7
source share
2 answers

From the documentation :

β€œIn all browsers, loading, scrolling and error events (for example, on an element) do not bubble. [...] Such events are not supported for use with delegation, but they can be used when the event handler is directly attached to the element that generates the event.

+9
source

The on method will handle events for the currently selected elements when it is executed first, or any future elements that raise a specific event corresponding to a particular selector. Since an element added to the page does not automatically generate a load event or any other type, your code will never be executed for your newly added elements.

You have two options. The first is to trigger a custom event whenever your new item is inserted. For example,

 $.get("/newElemnet", function(newElement) { $('#placeToInsertElement').append(newElement); $(newElement).trigger('newElementAdded'); }); 

Then your original function will listen for this custom event:

 $(function(){ $("body").on("newElementAdded", ".this_button", function() { console.log("its been loaded"); }); }); 

The second option is to constantly poll for new items, as described in this question .

+11
source

All Articles