Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

commented Apr 15, 2014

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

This comment has been minimized.

Copy link

commented Aug 19, 2014

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.