js Quick Solution to the Conflict Problem of Mouse Click and Double Click Events

  • 2021-07-02 23:27:33
  • OfStack

Situation 1

If both single-click (click) and double-click (dblclick) events are bound to an DOM object, when a double-click event occurs on the DOM object, the first click (click) triggers a single-click (click) event, the second (successive) double-click (dblclick) event, or the click (click) event (IE7 and firefox).

Solution:


<button onclick="test(1)" ondblclick="test(2)"></button>
<script language="javascript">
var i = 1;
function test(n)  {
i = n; 
var val = setTimeout("call();",250); 
if(i==2){
clearTimeout(val);
}
}
function  call()  { 
if(i==1){
alert('click');
}else if(i==2){
alert('dblclick');
}
} 
</script>

Explanation:

The first click records the click time, and sets the Timeout of the click event (250ms is more appropriate). The second click judges the time interval between the click time at this time and the last click. If it is less than the specified event interval (such as 250ms), it is judged as a double-click event, and clear has set Timeout (to avoid triggering the click event).

Type 2:


<title> Distinguish between click and double click -www.ofstack.com</title>
<script type="text/javascript">
var flag=0;
function clickTest()
{
 if(!flag)
 {
 setTimeout("tt2();",300);
 }
 flag++;
}
function reset()
{
 flag=0;
}
function singleClick()
{
 var result=document.getElementByIdx_x('result');
 result.innerHTML=result.innerHTML+"click<br>";
 reset();
}
function dobuleClick()
{
 var result=document.getElementByIdx_x('result');
 result.innerHTML=result.innerHTML+"dobule click<br>";
 reset();
}
function tt2()
{
 if(flag==1)
 {
 singleClick();
 }
 else
 {
 dobuleClick();
 }
}
</script>
</head>
<body>
<input type="button" ondblclick="clickTest();" onclick="clickTest();" value="click test" />
<div id="result"></div> 

Related articles: