1

Code :

<div id="container">
    <div id="link">Link</div>
</div>​

$('#link').click(function (e) {
    console.log("link");                
});

$('#container').mousedown(function (e) {
    console.log("container");                
});

I'd like that, when I click on #link, it will not fire the #container handler. Tried stopPropagation() or preventDefault(), but I think it is the wrong approch?

markzzz
  • 47,390
  • 120
  • 299
  • 507

2 Answers2

2

The mousedown handler fires before the click handler, hence you can't cancel the mousedown handler from the click handler as the mousedown event already bubbled up to the parent element.

Without modifying your other handlers, I'd simply add a mousedown handler to the inner element to stop the mousedown event propagation.

$('#link').click(function (e) {
    console.log("link");
}).mousedown(function (e) { //stops the mousedown event propagation from reaching
    e.stopPropagation();   //the parent element
});

$('#container').mousedown(function (e) {
    console.log("container");
});

Fiddle

If you are able to switch the handlers to handle the same event (e.g. both click), you will be able to call event.stopPropagation() from the inner element's handler as I did with the mousedown handlers above.

Fabrício Matté
  • 69,329
  • 26
  • 129
  • 166
0

According to these questions/answers:

Prevent parent container click event from firing when hyperlink clicked

How to prevent trigger container's event when trigger children's events in JQuery?

e.stopPropagation(); is the correct way to go.

http://jsfiddle.net/MN5KK/1/

Edit: I see you're using mousedown on the container and click on the link, the mouse down event will always fire before the click because click is on release.

Community
  • 1
  • 1
Michael
  • 421
  • 2
  • 10
  • 23