Is it possible with jQuery to prevent a click event on the same element from being executed, after a mousedown & mouseup event has just been fired.
Any help/examples would be appreciated.
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.
MouseDown occurs when the user presses the mouse button; MouseUp occurs when the user releases the mouse button.
If you wish suppress the click event you have add the statement event. preventDefault() in the click event handler only and not the mouseup event handler.
Mouseup is always firing before click, despite this order.
There's an awkward approach that is to disable the button when mousedown, and enable it after a short period, like 100ms. If the mouseup happens in this period, click won't be fired.
$('#btn').on('click', function() {
alert('clicked')
});
$('#btn').on('mousedown', function() {
var btn = $(this);
btn.attr('disabled', 'disabled');
setTimeout(function() { btn.removeAttr('disabled'); }, 100);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<body>
<button id='btn'>Click me</button>
</body>
In Chrome and Internet Explorer, not Firefox though, detaching and reattaching the element at mousedown or mouseup will prevent the click event to be triggered. In Internet Explorer, this trick does not catch double-clicks though (in Chrome it does).
But I wouldn't rely on this strange behavior, who knows if it won't change at some point. Also, beware that detaching and reattaching can also have side-effects ont the children of the detached element (iframes reloading, file fields reset, ...).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With