How can I dynamicaly append elements outside the event handler with the help of an element created by this event handler?

I made the following code to clarify the question:

Html:

<body>
<div class="static">This is a static div</div>
 <button class="add-dynamic-button">Click me to add a new button</button>
</body>

Js:

$(function(){
$('.add-dynamic-button').on("click",function(){
    $('body').append("<button class='dynamic-button'>Click me to add a dynamic div'</button>");
});
    $('.dynamic-button').on('click',function(){
        $('body').append("<div class='dynamic-div'>This is a dynamic div</div>");
});
});

And here is jsfiddle to test: http://jsfiddle.net/6ZN5J/

When I have the $('.dynamic-button').on('click') handler inside the first click handler, a .dynamic-div is added fine. But when I place it outside the first click handler scope (as in the example above), nothing happens. I initially thought that $.on works on any DOM element that is not yet created, but now it turns out that it works on new elements of the same class or type if they are already in the DOM or when $.on is placed inside the function that creates those elements. Can you clarify why this happens and whether there are any methods to allow for using event handlers on dynamically created elements outside the handler they were created with? Thanks

Answers


$() is a selector. It finds the element(s) that were in the document or the parent element from which you're peforming the whole query at the time you did it.

If you want further buttons bound to click event you'll need to manually bind them:

 $('body').append("<button class='dynamic-button'>Click me to add a dynamic div'</button>")
         .on("click", ....);

Need Your Help

calling function pointer of a member function from a function pointer vector

c++ vector function-pointers event-driven-design

i think this is mostly a syntax error ( though not captured during compilation, only at runtime does the error happen)

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.