Javascript events after dynamically adding content [duplicate]


This question is already answered here: How to use jquery plugins with dynamic content or why javascript falls off after AJAX (1 answer) Closed 3 years ago.

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.

Author: Deleted, 2013-07-15

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.

 3
Author: lampa, 2013-07-30 07:55:14

If on pure JS-see addEventListener()

 2
Author: dekameron, 2013-07-15 13:38:20

Try calling directly:

$(document).on('click', '.colorbox', function(e) {
  e.preventDefault();
  $.colorbox({href:$(this).attr('href'), open:true});
}
 1
Author: Гена Царинный, 2013-07-31 13:40:04

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).

100 % a working example is here

 1
Author: keenself.ru, 2015-09-26 20:25:21
$(document).on('click', '.your_added_element', function(e){
    // благодаря "делегированию событий" - событие сработает всегда
})
 0
Author: Denis Masster, 2013-07-15 20:41:43

jquery live already deprecated.
It is better to use on

 0
Author: Абляким Аблялимов, 2013-07-30 13:19:21

jquery live('click', callback) or on('click', callback)

 -1
Author: mountpoint, 2013-07-30 13:18:43