Reputation: 1051
<div id="main">
hello world
<div id="second-div">
bye
</div>
</div>
jQuery('#main:not(second-div)').click(function() {
alert('works!');
});
I want to detect mouse click on the "main" div, but the click event shouldn't trigger when I click on the "second-div" div. I've tried using ":not(second-div)" but the click triggers anyway.
Upvotes: 1
Views: 135
Reputation: 20240
You could check the target property of the event. (Edited to reflect the improvement proposal from the comment)
jQuery('#main').click(function(e) {
if(e.target===this) {
alert("works!");
}
});
Upvotes: 3
Reputation: 3747
Similar solution like the one provided by Daniel.
I always use is
to identifiy like this:
jQuery('#main').click(function(event) {
if(!$(event.target).is('#second-div'))
{
alert('works');
}
});
Upvotes: 2
Reputation: 1869
I know this is weird....
$(document).ready(function(){
$(this).click(function(e){
if($(e.originalEvent.originalTarget).prop('id')=='main'){
alert('You have clicked on Main')
}
})
});
Just wanted to share something that i have learned today....
Upvotes: 2
Reputation: 34107
Or you could try this: http://jsfiddle.net/N6G62/
This should help the cause :)
code
$('#main').click(function(e) {
alert('works!');
});
$('#main div').click(function(e) {
e.stopPropagation();
});
Upvotes: 2
Reputation: 4400
You should call
event.stopPropagation();
on the first line of your click handler. this shall stop the propagation of events in the heirarchy.
Upvotes: -1