JS implements the coexistence of mouse click and double click events

  • 2020-03-30 02:18:23
  • OfStack

It has long been assumed that in Web development, double-clicking events were used infrequently, until recently, when a project needed to bind two events, click and double-click, on a button. At first I thought it was just two events tied to the button... Only later did I realize that I had thought too simply that a double-click event would also trigger a single click

After some research, finally use JS "setTimeout" delay execution method, will click the delay of 300 milliseconds to execute the solution, the code is as follows:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head>    
<title></title>    
<mce:script src="jquery-1.6.min.js" mce_src="jquery-1.6.min.js" type="text/javascript"></mce:script>    
<mce:script type="text/javascript">
<!--        
$(function () {            
var num = 0;            
var timeFunName = null;            
$("button").bind("click", function () {                
//Cancel the method that was not executed in the last delay & NBSP;                            
clearTimeout(timeFunName);                
//Click & execute with a delay of 300 milliseconds;                            
timeFunName = setTimeout(function () {                    
num++;                    
$("textarea").val($("textarea").val() + " The first " + num + " Event name: click /n");                
}, 300);            }).bind("dblclick", function () {                
//Cancel the method that was not executed in the last delay & NBSP;                            
clearTimeout(timeFunName);                
num++;                
$("textarea").val($("textarea").val() + " The first " + num + " Event name: double click /n");            
});        
});    
// --></mce:script>
</head>
<body>    
<textarea rows="20" cols="50"></textarea><button type="button"> submit </button></body></html>


Related articles: