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:


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


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

And here is jsfiddle to test:

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


$() 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.