Reputation: 30731
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?
Upvotes: 8
Views: 4391
Reputation: 23074
You need to bind the .on()
to a parent.
What you're trying to do is - bind the handler to a parent that listens for an event, then checks whether the event was triggered by an element that matches that selector.
$("body").on("click", '.container',function(){
alert("outside the box?");
})
Updated fiddle here
Upvotes: 2
Reputation: 30145
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'
Upvotes: 5
Reputation: 78721
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.
Upvotes: 7
Reputation: 1252
According to the documentation for jQuery.on()
:
Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to
.on()
.
You will have to bind the event to a parent container. Perhaps something like THIS.
Upvotes: 1
Reputation: 160873
When you bind a event handler to a element use .on
, the target you bind to must exist in the domcument.
$('body').on('click', '.container > *', function(e){
e.stopPropagation();
});
$('body').on("click",'.container',function(){
alert("outside the box?");
})
Upvotes: 2