Why can't a mouseup event prevent a click event

beatgammit picture beatgammit · Aug 20, 2013 · Viewed 19.5k times · Source

jsfiddle

<div class='wrapper'>
    <button class='child'>Click me</button>
</div>

function h(e) {
    e.preventDefault();
    e.stopPropagation();
    e.stopImmediatePropagation();
    alert(e.type);
    return false;
}

document.querySelector('.wrapper').addEventListener('mouseup', h, false);
document.querySelector('.child').addEventListener('click', h, false);

I expect this to prevent the 'click' event from firing, but it doesn't. However, changing mouseup to mousedown does in fact prevent the click event.

I've also tried setting the useCapture argument to true, and that also doesn't produce the desired behavior with mouseup. I've tested this on Chrome and Firefox. Before I file bugs, I figured I'd ask here.

Is this a bug in current browsers, or is it documented behavior?

I've reviewed the W3C standard (DOM level 2), and I wasn't able to find anything that could explain this behavior, but I could have missed something.

In my particular case, I'm trying to decouple two pieces of code that listen to events on the same element, and I figured using capture events on the part that has priority would be the most elegant way to solve this, but then I ran into this problem. FWIW, I only have to support officially supported versions of FF and Chrome (includes ESR for FF).

Answer

Joseph Spens picture Joseph Spens · Oct 17, 2013

Check out this quirksmode article

The click event:

Fires when a mousedown and mouseup event occur on the same element.

So when the mouse click is released, both the mouseup and click events are fired, click doesn't wait for the mouseup callback to finish. Almost always, mouseup and click can be used synonymously.

In order to cancel the click, like you demonstrated, you can return false in the mousedown event callback which prevents the click event from ever completing.