Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't a mouseup event prevent a click event

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).

like image 534
beatgammit Avatar asked Aug 20 '13 18:08

beatgammit


People also ask

Does mouseup fire before click?

Mouseup is always firing before click, despite this order.

What is a mouseup event?

The mouseup event is fired at an Element when a button on a pointing device (such as a mouse or trackpad) is released while the pointer is located inside it. mouseup events are the counterpoint to mousedown events.

What is the difference between mouseup and Mousedown?

MouseDown occurs when the user presses the mouse button; MouseUp occurs when the user releases the mouse button.

What is the difference between Mousedown and click?

Note: This differs from the click event in that click is fired after a full click action occurs; that is, the mouse button is pressed and released while the pointer remains inside the same element. mousedown is fired the moment the button is initially pressed.


1 Answers

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.

like image 94
Joseph Spens Avatar answered Sep 29 '22 08:09

Joseph Spens