SoFunction
Updated on 2025-04-10

JS does not perfectly resolve conflicts between click and dblclick events

Condition description
When an element, such as: div, binds a click event and a dblclick event at the same time, and these two events have to handle relatively independent services, that is, dblclick cannot be triggered when clicking, and click cannot be triggered when dblclick. In actual tests, it was found that when dblclick, click will always appear once. This is the problem that will be solved below.
Situation analysis
First of all, we need to understand the execution order of click and dblclick. The test process is omitted. The following are the test results:
click:mousedown -- mouseup -- click
dblclick:mousedown -- mouseup -- click -- mousedown -- mouseup -- click -- dblclick
From this point of view, before dblclick is triggered, clicks are actually executed twice, and the first click will be blocked (why? It's so good, I don't know).
Solution
The first thing I thought about was whether the event could be stopped, but I found that the browser did not provide the corresponding method. If it was implemented by itself, it was too difficult because the behavior associated with the click event must be cancelled.
So I considered using delay, which is also the only solution I could think of. Use setTimeout() to delay the completion of the click event, and then use clearTimeout() to stop when the click needs to be blocked.
Specific code
Copy the codeThe code is as follows:

var test = (function(){
var clickText = 'click<br>';
var dblclickText = 'dblclick<br>';
var timer = null;
return {
click: function(){
clearTimeout(timer);
timer = setTimeout(function(){
$('body').append(clickText);
}, 300);
},
dblclick: function(){
clearTimeout(timer);
$('body').append(dblclickText);
},
init: function(){
$(function(){
$('div').click().dblclick();
});
}
}
})();
();

html code
Copy the codeThe code is as follows:

<div style="width:100px;height:100px;background:red;text-align:center;line-height:33px;-moz-user-select:none;-khtml-user-select:none;user-select:none">click<br>or<br>dblclick</div>

Subsequent
The title of the article says that it is imperfect, because under Windows, the control panel can adjust the double-click speed of the mouse (other systems are not clear), so the double-click speed I set in the system is slower, so the above demo will not take effect. So 300ms is just a rough one.
Author: Hu Rui