Javascript events after dynamically adding content [duplicate]
Tell me a convenient way to hang events on an element after it is dynamically added. For example, after loading the content via ajax
.
I need to work out a code similar to this: $('.colorbox').colorbox();
That is, I bind my events via $(document).on()
, so they work out. Events of third-party plugins are implemented differently, and therefore are not executed after dynamic loading content.
At the moment, I use $(document).ajaxSuccess()
to bind events of third-party plugins after loading content using ajax
.
I am interested in whether there is a more elegant solution to this problem.
7 answers
There are several ways to attach an event to a dynamic element.
The first is hanging the handler on some event, i.e.:
$(document).on('mouseover', '.element', function(){
if($(this).data('colorbox') != undefined) {
$('.colorbox').colorbox();
}
});
You can also play with DOM events: DOM events.
If on pure JS-see addEventListener()
Try calling directly:
$(document).on('click', '.colorbox', function(e) {
e.preventDefault();
$.colorbox({href:$(this).attr('href'), open:true});
}
JQuery works with elements that were on the page at the time of code initialization.
If new elements are added - using ajax or functions like append () - the events do not affect them.
How do I work with newly created DOM elements?
It turns out that delegated event handling is used for dynamic elements.
In short, the meaning of delegation is that handlers are "hung" not on elements that are not present in the dom, but on existing parent object.
Thus, when the corresponding event is triggered, this handler will be called for all elements corresponding to the selector, even if these elements were not present at the time of the handler declaration (for example, when the page loads).
$(document).on('click', '.your_added_element', function(e){
// благодаря "делегированию событий" - событие сработает всегда
})
jquery live
already deprecated.
It is better to use on
jquery live('click', callback)
or on('click', callback)