3

I am trying to check whether a click on an element is a single click or a double click.

I am trying with this code.

var clk_ch = document.getElementById('clk');

function singleClick() {
    alert("single click");
}

function doubleClick() {
    alert("double click");
}

var clickCount = 0;

clk_ch.addEventListener('click', function() {
    alert();
    clickCount++;
    if (clickCount === 1) {
        singleClickTimer = setTimeout(function() {
            clickCount = 0;
            singleClick();
        }, 400);
    } else if (clickCount === 2) {
        clearTimeout(singleClickTimer);
        clickCount = 0;
        doubleClick();
    }
}, false);

I am not getting any alert. Where am I going wrong? clk is the id of the clicked element

<input type="image" src="button.gif" id="clk" >
Erik
  • 2,137
  • 3
  • 25
  • 42
Alén
  • 125
  • 2
  • 9
  • possible duplicate of [how to differentiate single click event and double click event?](http://stackoverflow.com/questions/5497073/how-to-differentiate-single-click-event-and-double-click-event) – Rohit Arora Jul 08 '15 at 07:35
  • I think the answer here is better than the one in the link. – stevenw00 Jul 08 '15 at 07:38
  • This might help. It has a fiddle http://stackoverflow.com/a/7845282/2270492, FIDDLE:http://jsfiddle.net/KpCwN/4/ – Hemal Jul 08 '15 at 07:49
  • @stevenw00 the issue which was being discussed there is still replicated here. According to me it is duplicate and will result in the same answer. – Rohit Arora Jul 08 '15 at 08:54
  • @hemal instead of anchor tag can we do it for input type which contains image? – Alén Jul 08 '15 at 08:54

1 Answers1

4

No need of using setTimeout. You can add dblclick event listener.

document.addEventListener("DOMContentLoaded", function (event) {

    var clk_ch = document.getElementById('clk');

    clk_ch.addEventListener('click', singleClick, false);
    clk_ch.addEventListener('dblclick', doubleClick, false);

});

DEMO

In jquery:

$('#clk').on('click', singleClick).on('dblclick', doubleClick);

DEMO

Tushar
  • 85,780
  • 21
  • 159
  • 179