Skip to content

Instantly share code, notes, and snippets.

@karbassi
Created October 21, 2010 22:02
Show Gist options
  • Star 22 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save karbassi/639453 to your computer and use it in GitHub Desktop.
Save karbassi/639453 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;
}
@nickbuddendotcom
Copy link

If you also want to check for dragging:

    var clickCount     = 0,
         mouseMove   = function() {
          console.log('drag click');
          the_div.removeEventListener('mousemove', mouseMove);
          clear();
        },
        clear = function() {
          clickCount = 0;
          clearTimeout(singleClickTimer);
        },
        singleClickTimer;

    the_div.addEventListener('mousedown', function() {
      clickCount++;

      // Single Click
      if(clickCount === 1) {
        the_div.addEventListener('mousemove', mouseMove);

        singleClickTimer = setTimeout(function() {
          console.log('single click');
          clickCount = 0;
        }, 400);

      // Double Click
      } else if (clickCount === 2) {
        console.log('double click');
        clear();
      }
    }, false);

    window.addEventListener('mouseup', function() {
      _this.el.removeEventListener('mousemove', mouseMove);
    });

@paulkoegel
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment