1

I have a simple program like:

<div onclick="handleClick(event)" ondblclick="handleDoubleClick(event)">
  Hellooww world
</div>
<script>
    var a = false
    function handleClick(e) {
    if(a) {
        a = false
            console.log("Hellooww", a)
    }else{
        a = true
      console.log("Hellooww", a)
    }
    }

  function handleDoubleClick(e) {
    console.log("world")
  }
</script>

Here on single click it sets the value of a to true of false.. But when its double click it perfomrs both single click and double click

How can I check only for single click and double click

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
varad
  • 7,309
  • 20
  • 60
  • 112

1 Answers1

2

This thread provides details on why the behavior is happening, but here is the solution to your specific use case. The one possible approach is to use timeout and some wait time. The problem is that there is no standard interval to wait. Although you could use the 300 ms timing that a mobile browser uses to distinguish between tap and double tap event:

var a = false;
var timeout;
function handleClick(e) {
    timeout = setTimeout(function () {
        if (a) {
            a = false
            console.log("Hellooww", a)
        } else {
            a = true
            console.log("Hellooww", a)
        }
    }, 300);
}

function handleDoubleClick(e) {
    if (timeout) {
        clearTimeout(timeout);
    }
    console.log("world")
}

But generally, don't register click and dblclick events on the same element: it's impossible to distinguish correctly single-click events from click events that lead to a dblclick event.

Community
  • 1
  • 1
Max Koretskyi
  • 101,079
  • 60
  • 333
  • 488
  • 1
    How did you arrive at the 300ms? – Felix Kling Dec 14 '16 at 08:01
  • @FelixKling, that's a valid question :). I remember reading somewhere that it's the time a browser waits to distinguish a double click or another click event. Is this not true? – Max Koretskyi Dec 14 '16 at 08:02
  • I don't know, but having a resource to back this up would be great! – Felix Kling Dec 14 '16 at 08:03
  • @FelixKling, actually, it seems that this interval of `300` ms [is pertaining](https://www.sitepoint.com/5-ways-prevent-300ms-click-delay-mobile-devices/) to `tap` and `double tap` event, not sure if it applies to `click` and `dblclick`. I'll mention that in my answer. – Max Koretskyi Dec 14 '16 at 08:09
  • @Maximus it seems good approach but here when I double click it will log world in the console also it will execute `handleClick` at the end.. I dont want to execute `handleClick` when I do double click – varad Dec 14 '16 at 09:32
  • @aryan, yeah, this is tricky, it's because `click` is triggered two times, one before `dbclick` and one after. I thought the `click` after `dblclick` shouldn't be triggered. I don't know how to handle this situation – Max Koretskyi Dec 14 '16 at 09:39