Alon
Alon

Reputation: 7758

How to trigger an event on a parent but not on its child in jQuery

I have this piece of html:

<div id="parent">
     <div id="child></div>
</div>

and it looks graphically like this:

---------------------------
-                         -
-    #parent              -
-                         -
-         ----------      -
-         -        -      -
-         - #Child -      -
-         -        -      -
-         ----------      -
-                         -
---------------------------

How do I trigger an event in jQuery (roll over for example) that will work only when hovering on the #parent but will not work when hovering on the #child

Upvotes: 0

Views: 205

Answers (4)

d.k
d.k

Reputation: 4460

$('#parent').on('click',function(e){
    if(e.target === document.getElementById('child')) return false;
    // your code 
})

However in my point of view it will be better to resort to .stopPropagation(), as others said

Upvotes: 0

jbabey
jbabey

Reputation: 46647

If you return false from an event handler, it will stop the event from bubbling up to the next ancestor.

http://jsfiddle.net/jbabey/CV76D/

$('#outer').mouseover(function () {
    $(this).addClass('green');
});

$('#inner').mouseover(function () {
    return false;
});

Upvotes: 0

Danny
Danny

Reputation: 468

I think looking into event.stopPropagation would do the trick...

$("#someElement").click(function(event){
  event.stopPropagation();
  // do something
});  

http://api.jquery.com/event.stopPropagation/

Upvotes: 0

Hemant Metalia
Hemant Metalia

Reputation: 30638

you can use event.stopPropagation()

question similar to it is jquery stop child triggering parent event

$("#parent").click(function(event){
  //do something with parent

});
$("#child").click(function(event){
  event.stopPropagation();

});

Upvotes: 3

Related Questions