Using .on() and e.stopPropagation() on dynamic elements

javascript, jquery, jquery-events

Solution

In short word you need to put `on()` on existing parent element to make it works:

$('body').on('click', 'a', function(e){
    e.preventDefault();
    $('<div class="container"><div class="box"></div></div>').appendTo('body');
    $(this).remove();
});

$('body').on('click', '.container > *', function(e){
  e.stopPropagation();    
});

$('body').on('click', '.container', function(){
  alert("outside the box?");    
})​

Code: http://jsfiddle.net/GsLtN/5/

For more detail check '.on()' on official site at section 'Direct and delegated events'

Problem

I have been experimenting with capturing click events outside of elements using `stopPropagation()`. ``` $(".container").children().on('click',function(e){ e.stopPropagation(); }); $(".container").on("click",function(){ alert("outside the box?"); })​ ``` Here is a jsFiddle set up to demonstrate it functioning. An alert should fire when you click anywhere outside of the white box. Now, I am trying to have the same principle applied to dynamically created elements. As far as I understand, the `on()` method of event assignment in jQuery should allow this to function without changing the script. Here is a second jsFiddle where you must first click a link to create the elements. Once you have done this, the theory is that the same script will work, but it does not. What am I missing about this method?

Original source