Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding event to dynamically added elements to DOM using jQuery

Tags:

html

jquery

dom

I'm dynamically adding few elements to DOM. And I want to manipulate these element behavior using .on() function of jQuery. But somehow DOM is not firing .on() event for dynamically added elements.

Here is JS Fiddle that shows the example - http://jsfiddle.net/jYQ2D/1/

When I click on "Dynamically Added in HTML" button, it should show alert message but it is not showing.

Any idea why?

like image 850
Wiz Avatar asked Dec 20 '22 10:12

Wiz


1 Answers

Delegation via .on doesn't work that way. You have to call .on on the element and then use the second argument as the delegation selector:

$(document).on("click", "#dyna", function() { 

http://jsfiddle.net/jYQ2D/2/

Documentation. Also be aware that there can be only one #dyna element.

like image 113
Explosion Pills Avatar answered Dec 29 '22 00:12

Explosion Pills