1

Possible Duplicate:
jquery: on vs live

I used to use .live() method when I have dynamically created objects by javascript, because at the time I declare the event listener to a click for instance, the element isn't in the DOM yet, so when the element is added dynamically by an user action, the .live('click') method would do the trick.

But, in jQuery v1.9.0, there's no live method, the documentation advises to use .on() instead, but that doesn't work in this kind of example ...

Here is a fiddle with an example: http://jsfiddle.net/promatik/C3DLQ/.

It will only work if you set the jQuery to 1.8.3 or the Migrate Plugin.

$("#create").click(function(){
    $('body').append($('<div id="test" class="btn">click me<div>'));
});

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

I actually tested other methods like delegate() and bind(), but none worked.

Community
  • 1
  • 1
António Almeida
  • 8,450
  • 5
  • 54
  • 59

3 Answers3

3

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/

John Koerner
  • 35,668
  • 7
  • 74
  • 128
2

You can attach it to the document and specify a selector, like so:

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

The #test element wasn't returned on your initial selector query, so no event was attached. Attaching it to the document element and specifying a selector to use will make it work when new elements are added to the DOM.

Marc Baumbach
  • 9,670
  • 2
  • 25
  • 44
1

The reason it's not working is because you are using multiple instances of one ID. Use classes instead when selecting more than one element.

$('#create').click(function() {
    $('body').append($('<div class="btn test">click me<div>'));
});

Also you need to bind the click to the document and filter the element to .test like this.

$(document).on('click', '.test', function() {
    alert('worked!'); 
});
Austin Brunkhorst
  • 18,784
  • 5
  • 40
  • 56