Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 324
Mild Fuzz Avatar asked Aug 23 '12 09:08

Mild Fuzz


2 Answers

When the item is added dynamically, you should attach the handler to the closest parent that will surely be there - in your case this is body. You can use on() this way to achieve a functionality that delegate() used to offer:

$(selector-for-parent).on(events, selector-for-dynamic-children, handler);

So your code rewritten would simply be this:

$("body").on('click', '.container', function(e){
    var $target = $(e.target);
    if ($target.hasClass('container')) {
        alert("outside the box!");
    }
});

I used e.target to find which element actually triggered the event. In this case, I identify the item by checking whether it has the container class.

jsFiddle Demo

like image 69
kapa Avatar answered Sep 28 '22 18:09

kapa


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'

like image 42
Samich Avatar answered Sep 28 '22 17:09

Samich