I want to bind click and dblclick event on same DOM
, but dblclick always active click event. How to do that two events don't influence each other!
Asked
Active
Viewed 799 times
2

MANOJ GOPI
- 1,279
- 10
- 31

LeiLei Yang
- 21
- 2
-
1possible duplicate of [how to differentiate single click event and double click event?](http://stackoverflow.com/questions/5497073/how-to-differentiate-single-click-event-and-double-click-event) – Lorenzo Marcon Feb 03 '15 at 08:29
3 Answers
1
Wait to respond to the click by a tiny amount via setTimeout
, and don't do the click action if you see the double-click. Unfortunately, the timing is pretty tricky — too little and you get the click when you shouldn't, too much and clicks really lag.
const div = document.getElementById("the-div");
let clickTimer = 0;
div.addEventListener(
"click",
function () {
clearTimeout(clickTimer);
clickTimer = setTimeout(function () {
console.log("clicked");
clickTimer = 0;
}, 250);
},
false
);
div.addEventListener(
"dblclick",
function () {
clearTimeout(clickTimer);
console.log("double-clicked");
},
false
);
#the-div {
user-select: none;
}
<div id="the-div">Click and/or double-click me</div>

T.J. Crowder
- 1,031,962
- 187
- 1,923
- 1,875
-
@LeiLeiYang - Thanks for the edit! If you run across others of these, please also remove the `script` tag that (tries to) include the old snippet log stuff. – T.J. Crowder Dec 07 '22 at 09:11
1
if you use jquery, you can extend the jquery plugin. Using the javascript's non-blocking feature, and callback feature to handle this question. You can try this plugin: https://github.com/sgyyz/jquery-oneordoubleclick which apply for your jquery module.
$target_node.oneordoubleclick({oneclick: function(){
console.log('you have click this node.');
}, dbclick: function() {
console.log('you have double click this node.');
}
});

Troy Young
- 181
- 1
- 12
0
Here's a demo using setTimeout
that you can handle your click
and dblclick
events separately. Using a bool
variable you can decide if it's a single click or double click and create handler accordingly.
HTML :
<div>Bingo</div>
CSS :
div{
width : 100px;
height : 100px;
background-color: blue;
}
javaScript :
var div = document.getElementsByTagName("div")[0];
var isSingleClick = true;
div.onclick = function(){
setTimeout(function(){
if(isSingleClick){
console.log("Click");
}
}, 500);
};
div.ondblclick = function(){
console.log("DBLClick");
isSingleClick = false;
setTimeout(function(){
isSingleClick = true;
}, 500);
};

Md Ashaduzzaman
- 4,032
- 2
- 18
- 34