Im trying to run a function on an element (.this_button
) that is being loaded dynamically. Im using the following code:
$(function(){
$(\"b
The on
method will handle events for the currently selected elements when it is first executed or any future elements that raise a particular event that match a specific selector. Since an element being added to a page does not automatically raise a load
or some other type of event, 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 element is being inserted. For instance,
$.get("/newElemnet", function(newElement) {
$('#placeToInsertElement').append(newElement);
$(newElement).trigger('newElementAdded');
});
Then your original function would listen for that custom event:
$(function(){
$("body").on("newElementAdded", ".this_button", function() {
console.log("its been loaded");
});
});
The second option is to constantly poll for the new elements as described in this question.
From the documentation:
"In all browsers, the load, scroll, and error events (e.g., 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 generating the event."