2

I have some div called mydiv. I have a click event attached to it. Inside of the div I have a link. I want the event not to be triggered after clicking on the link. Smth like

$(document).on('click', '#mydiv a', function(){
    // How to disable parent's event here?
});

Thank you!

Volodymyr
  • 1,557
  • 2
  • 14
  • 21
  • Possible duplicate of http://stackoverflow.com/questions/2728252/jquery-stoppropagation-bubble-down – zewa666 Aug 08 '13 at 11:24

3 Answers3

3

The problem you have is that the click handler bound to the div will trigger first because the delegated event will only fire once the event has propagated right up to the document.

In your #mydiv click handler, check that the event.target === this before executing any code, that way, it'll only fire when the div has been clicked.

Something like this:

$('#mydiv').on('click', function(e) {
    if (e.target === this) {
      alert('div click fired!'); 
    }
});

$(document).on('click', '#mydiv a', function(e) {
   alert('anchor click fired!'); 
});

Here's a fiddle


Edit If the only reason you're attaching an event handler to the anchor is to prevent triggering the click handler on the div, just check if the target is not an anchor in the div click handler before doing anything else:

$('#mydiv').on('click', function(e) {
    if ($(e.target).is('a')) {
        return;
    }
    alert('div click fired!'); 
});

Here's another fiddle

billyonecan
  • 20,090
  • 8
  • 42
  • 64
  • The problem is that the event attached to the parent was attached by Galleria plugin and I don't know how was it attached... – Volodymyr Aug 08 '13 at 11:40
2

This should do what you're looking for:

$(document).on('click', '#mydiv a', function(e){
    // How to disable parent's event here?
    e.stopPropagation();
});
David MacCrimmon
  • 966
  • 1
  • 6
  • 19
  • From jQuery's docs, am I misunderstanding? "Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event." – David MacCrimmon Aug 08 '13 at 11:31
  • 1
    It would work if the event hadn't been delegated. The event handler is attached to the document, so it only fires once it has reached the document, by which time the click handler on the `div` has already fired – billyonecan Aug 08 '13 at 11:32
  • You can also use single JQuery for click event on div as well as to prevent click event on its child – Coder Aug 08 '13 at 11:35
0

Try this so you can use single JQuery

HTML

<div id="mydiv">
    <span> Hello, How are you? </span>
    <a id="alink" href="#"> Click ME </a>
</div>

JQUERY

$(document).on('click', '#mydiv', function(event){
   alert("You clicked on Div Span");
 }).children().find("#alink").click(function(e) {
  return false;
});

JSFiddle Demo

Coder
  • 6,948
  • 13
  • 56
  • 86