Skip to content

Instantly share code, notes, and snippets.

@cereal-s
Forked from karbassi/index.html
Created September 7, 2017 09:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cereal-s/9eddc14d87270a5286163a64eee466ca to your computer and use it in GitHub Desktop.
Save cereal-s/9eddc14d87270a5286163a64eee466ca to your computer and use it in GitHub Desktop.
How to handle single and double click events separately in javascript.
<!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>
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);​
#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