Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent click event after mousedown & mouseup event

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.

like image 797
Elliot Avatar asked May 24 '12 23:05

Elliot


People also ask

Do the mouse events click and Mousedown have the same functionality?

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.

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.

How do I get rid of MouseUp event?

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.

Does MouseUp fire before click?

Mouseup is always firing before click, despite this order.


2 Answers

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>
like image 177
neuront Avatar answered Oct 25 '22 00:10

neuront


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

like image 21
Louis Ameline Avatar answered Oct 25 '22 01:10

Louis Ameline