Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - cannot bind events to dynamic elements?

I've come to maintain a piece of javascript that downloads some JSON data from the server, builds a new table row (like $('<tr></tr')) and inserts it into the document.

The a node is, at one point created like this:

var a = $('<a class="foo" href="#"></a>');

and later, an event is bound to it like this:

a.click(function () {
  // yadda yadda

  return false;
});

The only problem is that this doesn't seem to work. Neither does binding through on() or the deprecated live(). The handler is simply "ignored", never fires and the page scrolls to the top (due to the href="#"). When binding the event, the element is already appended to DOM. Any help would be greatly appreciated.

Some contextual information that comes to mind: the element is created inside a loop iterating over the data, but that shouldn't be a problem unless javascript has some really weird stuff going on with scoping, plus everything else I try with the element works: I can change its content, styling, only the event binding doesn't work. And of course, the jQuery version, which is 1.8.3.

like image 868
Jakub Lédl Avatar asked Nov 30 '12 17:11

Jakub Lédl


2 Answers

EDITED

The .on() should be set up like this to work with dynamically created elements. Also, make sure to use Jquery version 1.8 (newest release)

Also, you need to prevent the standard action of the click if you don't want to scroll to the top.

Here is a working FIDDLE

var a = $('<a class="foo" href="#">ASD</a>');

a.appendTo($("body"));

$('body').on('click', 'a', function(e) {
    e.preventDefault();
    $(this).after('<br/><a class="foo" href="#">ASD</a>');
});
like image 114
VIDesignz Avatar answered Nov 13 '22 04:11

VIDesignz


You have various options. You can bind to the element or to the document. 

BIND TO DOCUMENT:

 $(document).on("click", "a.foo", function(event){
//do stuff here 
 });

When you bind to a document, you can freely create and destroy a.foo elements and they will all respond to your function.

BIND TO ELEMENT:

$("a.foo").on("click", function(event){
//do stuff here
  });

When you bind to an element, the function is bound to all previously existing elements ONLY. So make sure you do this at the end of document load or at the end of your function.

I would recommend always binding to document!

like image 24
Federico Avatar answered Nov 13 '22 02:11

Federico