Jquery .Live() VS .On() Method For Adding a Click Event After Loading Dynamic Html

jQuery .live() vs .on() method for adding a click event after loading dynamic html

If you want the click handler to work for an element that gets loaded dynamically, then you set the event handler on a parent object (that does not get loaded dynamically) and give it a selector that matches your dynamic object like this:

$('#parent').on("click", "#child", function() {});

The event handler will be attached to the #parent object and anytime a click event bubbles up to it that originated on #child, it will fire your click handler. This is called delegated event handling (the event handling is delegated to a parent object).

It's done this way because you can attach the event to the #parent object even when the #child object does not exist yet, but when it later exists and gets clicked on, the click event will bubble up to the #parent object, it will see that it originated on #child and there is an event handler for a click on #child and fire your event.

jquery: on vs live

.on combines and replaces .bind, .live, and .delegate. The syntax $('selector').on('event', callback) is the moral equivalent of bind, not live.

Add a filtering selector to your call to on:

$('container').on('click', 'child-filter', callback);

In this case,

$('.a').on("click", ".alert-link", function(){
alert('abc');
return false;
});

This was changed because it is more efficient to attach a delegate handler to a more localized container element than the old .live style of attaching the handler to the root of the DOM.

In other words, even though alert-link elements will only appear inside of a small a div, with .live, jQuery listens to every single click event on the page and compares it to the delegated selector. By being more targeted, jQuery only has to process clicks on elements within a.

What to use instead of .live() for elements added after event declaration (jQuery v1.9)

The reason it is not working is that test did not exist when the javascript first ran. If you attach the on event to the parent element and filter it to #test, then it will work as expected.

$("body").on("click", "#test", function(){
alert("worked!");
});

Updated fiddle: http://jsfiddle.net/C3DLQ/4/

Binding a click event to entities loaded dynamically using jQuery on()

There is no load event triggered by loading via ajax so trying to use it won't accomplish anything.

In addition, it looks like you have duplicate ids in the content. An id must be unique in the document and trying to use a selector to find duplicate ids won't work. You should be using a class name.

Probably, the better way to solve the event handlers on dynamically loaded elements is to use delegated event handling on a class name in the content.

If you change your HTML to a class name like this:

<a class="deleteTrigger" href="#">Delete</a>

Then, assuming the top of the table isn't loading dynamically you can bind to it with delegated event handling like this:

$(".datagrid").on("click", ".deleteTrigger", function(e) {
// click handler for delete button
});

If even the top of the table is loaded dynamically, then you can change to other static parent higher up in the DOM (you should pick a parent as close to the content as possible as long as it is not dynamically loaded) like this:

$("selector of some static parent").on("click", ".deleteTrigger", function(e) {
// click handler for delete button
});

You can see these other references on delegated event handling with .on():

jQuery .live() vs .on() method for adding a click event after loading dynamic html

jQuery .on does not work but .live does

Does jQuery.on() work for elements that are added after the event handler is created?

How do I attach events to dynamic HTML elements with jQuery?

I am adding a new answer to reflect changes in later jQuery releases. The .live() method is deprecated as of jQuery 1.7.

From http://api.jquery.com/live/

As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live().

For jQuery 1.7+ you can attach an event handler to a parent element using .on(), and pass the a selector combined with 'myclass' as an argument.

See http://api.jquery.com/on/

So instead of...

$(".myclass").click( function() {
// do something
});

You can write...

$('body').on('click', 'a.myclass', function() {
// do something
});

This will work for all a tags with 'myclass' in the body, whether already present or dynamically added later.

The body tag is used here as the example had no closer static surrounding tag, but any parent tag that exists when the .on method call occurs will work. For instance a ul tag for a list which will have dynamic elements added would look like this:

$('ul').on('click', 'li', function() {
alert( $(this).text() );
});

As long as the ul tag exists this will work (no li elements need exist yet).

Click event doesn't work on dynamically generated elements

The click() binding you're using is called a "direct" binding which will only attach the handler to elements that already exist. It won't get bound to elements created in the future. To do that, you'll have to create a "delegated" binding by using on().

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time.

Source

Here's what you're looking for:

var counter = 0;

$("button").click(function() {

$("h2").append("<p class='test'>click me " + (++counter) + "</p>")

});

// With on():

$("h2").on("click", "p.test", function(){

alert($(this).text());

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>

<h2></h2>

<button>generate new element</button>

Replacing deprecated .live with .on

The problem is that .box element is created after the dom is ready, so the element doesn't exist for it to attach an event to.

You need to add the event handler to an element that already exists.

http://jsfiddle.net/DBfKz/72/

I changed your event to look like:

$("#container").on("click", '.box a', function(e) {
$(e.target).parent().remove();
updateLinkAndCounter();
});

Also changed your version of jQuery from 1.4.4 to 1.8.3

It works the same way now.

empty() method interrupts dynamic event

Static event handlers are attached to a specific DOM element. If you remove that DOM element (which you are doing with .empty() and create a new DOM element (which you are doing with .append(), the original event handler attached to the now removed DOM element is gone.

In jQuery, it feels like you are attaching an event to a selector, but when you use the static form of .on() or .click() (like you are), the selector is evaluated once when you initially install the event handler. That selector turns into a list of DOM elements and those DOM elements at that specific time get the event handler attached to them. If you later create new DOM elements that also match that selector, they won't have any event handlers on them.

Delegated event handling can be used to solve this issue for some types of events.

Your options are:

  1. Don't replace the DOM element (perhaps just replace its content)
  2. Attach the event handler to the newly created DOM element after you create the new DOM element.
  3. Use delegated event handling which attaches the event handler to a much higher level DOM object (a parent you are not removing) and looks for events that occurred on child objects that have bubbled up to the static parent.

If you want to read more about delegated event handling, here are some other answers that explain it:

Does jQuery.on() work for elements that are added after the event handler is created?

jQuery .on does not work but .live does

jQuery .live() vs .on() method for adding a click event after loading dynamic html

JQuery Event Handlers - What's the "Best" method



Related Topics



Leave a reply



Submit