-
-
Save cereal-s/9eddc14d87270a5286163a64eee466ca to your computer and use it in GitHub Desktop.
How to handle single and double click events separately in javascript.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="utf-8" /> | |
<title>Single and Double Click</title> | |
<link rel="stylesheet" type="text/css" href="style.css"> | |
</head> | |
<body> | |
<div id="the_div"></div> | |
<span>Double click the block</span> | |
<script src="single-v-double.js" type="text/javascript"></script> | |
</body> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var the_div = document.getElementById('the_div'); | |
function singleClick() { | |
the_div.style.backgroundColor = '#0F0'; | |
} | |
function doubleClick() { | |
the_div.style.backgroundColor = '#00F'; | |
} | |
var clickCount = 0; | |
the_div.addEventListener('click', function() { | |
clickCount++; | |
if (clickCount === 1) { | |
singleClickTimer = setTimeout(function() { | |
clickCount = 0; | |
singleClick(); | |
}, 400); | |
} else if (clickCount === 2) { | |
clearTimeout(singleClickTimer); | |
clickCount = 0; | |
doubleClick(); | |
} | |
}, false); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#the_div { | |
background-color: #F00; | |
height: 300px; | |
width: 300px; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment