Im trying to run a function on an element (.this_button
) that is being loaded dynamically. Im using the following code:
$(function(){
$("body").on("load", ".this_button", function() {
console.log("its been loaded");
});
});
I tried delegate
, but it says its been deprecated in favor of on
. Some elements might be pushed, say after the document's been loaded for 10 minutes already. How can it continually check if an element .this_button
has entered the body?
Anyone know why this isnt working?
The delegate() method attaches one or more event handlers for specified elements that are children of selected elements, and specifies a function to run when the events occur. Event handlers attached using the delegate() method will work for both current and FUTURE elements (like a new element created by a script).
The onload event can only be used on the document(body) itself, frames, images, and scripts. In other words, it can be attached to only body and/or each external resource. The div is not an external resource and it's loaded as part of the body, so the onload event doesn't apply there.
Event delegation refers to the process of using event propagation (bubbling) to handle events at a higher level in the DOM than the element on which the event originated. It allows us to attach a single event listener for elements that exist now or in the future. Inside the Event Handling Function.
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."
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With