161

I have a single button in li with id "my_id". I attached two jQuery events with this element

1.

$("#my_id").click(function() { 
    alert('single click');
});

2.

$("#my_id").dblclick(function() {
    alert('double click');
});

But every times it gives me the single click

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
user426795
  • 11,073
  • 11
  • 35
  • 35
  • The single click will always have to fire, it's impossible to know if a double click is going to occur unless it actually occurs within the specified double click time. – Pieter Germishuys Mar 31 '11 at 08:29
  • 8
    This is possible, check my answer. You have to wait few ms after the first click and check if there is a new click until the specified time. In that way, you are able to know if this is just a simple or a double click. – Adrien Schuler Mar 31 '11 at 08:45
  • A drawback in how things are wired in life, if you care to distinguish between and make use of both events then you may need to delay the single click action until you know if there is a double in the making. If you have reasons to not fire both. – Gunnar Forsgren - Mobimation Apr 08 '22 at 12:49
  • Some timer usage example here. https://stackoverflow.com/questions/61461518/javascript-how-prevent-dblclick-double-click-to-also-fire-a-single-click-even – Gunnar Forsgren - Mobimation Apr 08 '22 at 13:01
  • I found the following 3 answers helpful in understand all the concepts: 1. [order of events](https://stackoverflow.com/a/5511527/6908282), 2. [`event.detail` to differentiate single-click with double-click](https://stackoverflow.com/a/53939059/6908282), 3. [modern solution using timeout](https://stackoverflow.com/a/60177326/6908282) – Gangula May 15 '23 at 12:46

22 Answers22

104

Instead of utilizing more ad-hoc states and setTimeout, turns out there is a native property called detail that you can access from the event object!

element.onclick = event => {
   if (event.detail === 1) {
     // it was a single click
   } else if (event.detail === 2) {
     // it was a double click
   }
};

Modern browsers and even IE-9 supports it :)

Source: https://developer.mozilla.org/en-US/docs/Web/API/UIEvent/detail

kyw
  • 6,685
  • 8
  • 47
  • 59
  • The best answer :) – sk8terboi87 ツ Jan 01 '19 at 08:09
  • 23
    In the case of double clicks, a single click (where `event.detail === 1`) will still trigger. See my [fiddle](https://jsfiddle.net/tsyrak/0y8uqemc/4/) or [this comment on this thread](https://stackoverflow.com/questions/880608/prevent-click-event-from-firing-when-dblclick-event-fires#comment95729771_29993141). – Fabien Snauwaert Jan 31 '19 at 14:37
  • Good point @FabienSnauwaert. I guess we can't bind both single and double click event handler on a particular element; the method above is useful to definitively determine a double click without resorting to stuffs like timer. – kyw Feb 07 '19 at 00:49
  • 2
    You still need a timer on that first click to not fire. Check my answer below https://stackoverflow.com/questions/5497073/how-to-differentiate-single-click-event-and-double-click-event/60177326#60177326 –  Feb 11 '20 at 21:06
  • 12
    Just an accessibility note: if a click event is fired by a keyboard (for example, when a user tabs to focus a button and press enter), the event is generated with the detail property as 0, so doing something like `if(evt.detail !== 1) return;` to reject accidental double clicks will block access to that button for users without a mouse. – gristow May 05 '20 at 20:43
  • `evt.detail` will also track additional clicks beyond a double-click (e.g. triple-click). – CubicleSoft Jun 20 '20 at 06:26
88

The behavior of the dblclick event is explained at Quirksmode.

The order of events for a dblclick is:

  1. mousedown
  2. mouseup
  3. click
  4. mousedown
  5. mouseup
  6. click
  7. dblclick

The one exception to this rule is (of course) Internet Explorer with their custom order of:

  1. mousedown
  2. mouseup
  3. click
  4. mouseup
  5. dblclick

As you can see, listening to both events together on the same element will result in extra calls to your click handler.

rxgx
  • 5,089
  • 2
  • 35
  • 43
  • 1
    not sure `dblclick` is even reliable... if I click once... wait a second or two, then click again, I get a `dblclick` event on the second click! – Michael Feb 15 '17 at 17:39
  • Such long clicks are useful for example for renaming files. It would be nice if there were parameter like 'longClick' to distinguish it. – PeterM Oct 25 '18 at 12:14
  • 2
    When `event.detail` is available, it is the best way to detect a double-click from the click handler. See [this answer](https://stackoverflow.com/a/53939059/39396). – Carl G Nov 14 '19 at 19:16
  • Downvoted, but not because the answer is wrong or bad, but because it is obsolete with IE bascially not being used anymore with a market share of 1%. – Waruyama Sep 09 '20 at 14:54
78

You need to use a timeout to check if there is an another click after the first click.

Here is the trick:

// Author:  Jacek Becela
// Source:  http://gist.github.com/399624
// License: MIT

jQuery.fn.single_double_click = function(single_click_callback, double_click_callback, timeout) {
  return this.each(function(){
    var clicks = 0, self = this;
    jQuery(this).click(function(event){
      clicks++;
      if (clicks == 1) {
        setTimeout(function(){
          if(clicks == 1) {
            single_click_callback.call(self, event);
          } else {
            double_click_callback.call(self, event);
          }
          clicks = 0;
        }, timeout || 300);
      }
    });
  });
}

Usage:

$("button").single_double_click(function () {
  alert("Try double-clicking me!")
}, function () {
  alert("Double click detected, I'm hiding")
  $(this).hide()
})
<button>Click Me!</button>

EDIT:

As stated below, prefer using the native dblclick event: http://www.quirksmode.org/dom/events/click.html

Or the one provided by jQuery: http://api.jquery.com/dblclick/

Kijewski
  • 25,517
  • 12
  • 101
  • 143
Adrien Schuler
  • 2,395
  • 1
  • 21
  • 32
  • 20
    This might seem to work nicely in general but doesn't the lag time allowed between clicks (by which two clicks are interpreted as a double-click) differ by system configuration? It's probably safer to rely on the ```dblclick``` event – jrz Apr 23 '13 at 15:52
  • 1
    Yeah I think you're right, `dblclick` is definitively the way to go today. jQuery also handles this event: http://api.jquery.com/dblclick/ – Adrien Schuler Apr 23 '13 at 16:08
  • 15
    @AdrienSchuler - From the doc you link: *It is inadvisable to bind handlers to both the click and dblclick events for the same element.* Question is about having *both*. – Álvaro González Apr 23 '13 at 17:04
  • 1
    When `event.detail` is available, it is the best way to detect a double-click from the click handler. See [this answer](https://stackoverflow.com/a/53939059/39396). – Carl G Nov 14 '19 at 19:16
  • Nice solution Adrien, i need it for a case where we have a single and a double click event on one object and just one should be fired. Therefore your solution is perfect for me. I just improved it a little bit to get "this" under control: https://playcode.io/492022 – BernhardS Jan 31 '20 at 10:52
39

The modern correct answer is a mix between the accepted answer and @kyw 's solution. You need a timeout to prevent that first single click and the event.detail check to prevent the second click.

const button = document.getElementById('button')
let timer
button.addEventListener('click', event => {
  if (event.detail === 1) {
    timer = setTimeout(() => {
      console.log('click')
    }, 200)
  }
})
button.addEventListener('dblclick', event => {
  clearTimeout(timer)
  console.log('dblclick')
})
<button id="button">Click me</button>
27

A simple function. No jquery or other framework is required. Pass your functions as parameters

<div onclick="doubleclick(this, function(){alert('single')}, function(){alert('double')})">click me</div>
    <script>
        function doubleclick(el, onsingle, ondouble) {
            if (el.getAttribute("data-dblclick") == null) {
                el.setAttribute("data-dblclick", 1);
                setTimeout(function () {
                    if (el.getAttribute("data-dblclick") == 1) {
                        onsingle();
                    }
                    el.removeAttribute("data-dblclick");
                }, 300);
            } else {
                el.removeAttribute("data-dblclick");
                ondouble();
            }
        }
    </script>
Renzo Ciot
  • 3,746
  • 2
  • 25
  • 29
  • 2
    I think this should be the best answer.However, I had to reduce the timeout to 200 for it to work on Windows IE8, but this value may be OS and user dependent. And also saved the timer reference to be able to cancel the execution of the click if a double click is registered. – xpereta May 03 '13 at 09:12
  • Thank you for this piece of code, it works great on chrome and firefox (although chrome doesn't need this hack to work with dbl and single). – victor Nov 28 '14 at 15:16
  • using `el.dataset.dblclick` would be a nicer way of doing this now. – WORMSS Feb 25 '16 at 09:32
  • When `event.detail` is available, it is the best way to detect a double-click from the click handler. See [this answer](https://stackoverflow.com/a/53939059/39396). – Carl G Nov 14 '19 at 19:16
12

I'm afraid that the behaviour is browser dependent:

It is inadvisable to bind handlers to both the click and dblclick events for the same element. The sequence of events triggered varies from browser to browser, with some receiving two click events before the dblclick and others only one. Double-click sensitivity (maximum time between clicks that is detected as a double click) can vary by operating system and browser, and is often user-configurable.

http://api.jquery.com/dblclick/

Running your code in Firefox, the alert() in the click() handler prevents you from clicking a second time. If you remove such alert, you get both events.

Álvaro González
  • 142,137
  • 41
  • 261
  • 360
  • 1
    When `event.detail` is available, it is the best way to detect a double-click from the click handler. See [this answer](https://stackoverflow.com/a/53939059/39396). – Carl G Nov 14 '19 at 19:16
11

Well in order to double click (click twice) you must first click once. The click() handler fires on your first click, and since the alert pops up, you don't have a chance to make the second click to fire the dblclick() handler.

Change your handlers to do something other than an alert() and you'll see the behaviour. (perhaps change the background color of the element):

$("#my_id").click(function() { 
    $(this).css('backgroundColor', 'red')
});

$("#my_id").dblclick(function() {
    $(this).css('backgroundColor', 'green')
});
bradley.ayers
  • 37,165
  • 14
  • 93
  • 99
8

This answer is made obsolete through time, check @kyw's solution.

I created a solution inspired by the gist posted by @AdrienSchuler. Use this solution only when you want to bind a single click AND a double click to an element. Otherwise I recommend using the native click and dblclick listeners.

These are the differences:

  • Vanillajs, No dependencies
  • Don't wait on the setTimeout to handle the click or doubleclick handler
  • When double clicking it first fires the click handler, then the doubleclick handler

Javascript:

function makeDoubleClick(doubleClickCallback, singleClickCallback) {
    var clicks = 0, timeout;
    return function() {
        clicks++;
        if (clicks == 1) {
            singleClickCallback && singleClickCallback.apply(this, arguments);
            timeout = setTimeout(function() { clicks = 0; }, 400);
        } else {
            timeout && clearTimeout(timeout);
            doubleClickCallback && doubleClickCallback.apply(this, arguments);
            clicks = 0;
        }
    };
}

Usage:

var singleClick = function(){ console.log('single click') };
var doubleClick = function(){ console.log('double click') };
element.addEventListener('click', makeDoubleClick(doubleClick, singleClick));

Below is the usage in a jsfiddle, the jQuery button is the behavior of the accepted answer.

jsfiddle

A1rPun
  • 16,287
  • 7
  • 57
  • 90
  • 2
    The code above and the 'Vanilla' version of your fiddle don't work ... here is a fixed Vanilla version : http://jsfiddle.net/jeum/cpbwx5vr/19/ – jeum Mar 22 '16 at 10:41
  • @jeum It still does the trick for me in every browser. What "does not work" and what do you expect? It looks like your version is not doing what I intented. – A1rPun Mar 22 '16 at 12:31
  • Fist I have modified my version (removed double closure), please try the new one : http://jsfiddle.net/jeum/cpbwx5vr/20/ The problem with your fiddle (Vanilla version) is that the double-click triggers the single handler : it retrieves single + double for me. – jeum Mar 22 '16 at 15:34
  • @jeum That one gives an error. Yeah my answer differs from the accepted and other answers here and I also specify this difference in this line: *Fire a click, then a doubleclick (don't go straight to doubleclick)* – A1rPun Mar 22 '16 at 15:47
  • 1
    Yes error again, so this version respond to the main question : http://jsfiddle.net/jeum/cpbwx5vr/21/. Now regarding your version (it's true that I had not understood), have you noticed that 'jQuery' don't achieve what you want in your fiddle ? – jeum Mar 22 '16 at 16:07
  • @jeum Yes I know. The jQuery version is the accepted answer and it does not what I want, it was just to show what the differences are. The problem with your fiddle is that the click gets delayed with a `setTimeout`, this breaks user experience for me. – A1rPun Mar 22 '16 at 16:25
  • Yes but to strictly differentiate click/dblclick what you point is inevitable (?) I have posted it as an answer. Thanks. – jeum Mar 22 '16 at 17:13
  • When `event.detail` is available, it is the best way to detect a double-click from the click handler. See [this answer](https://stackoverflow.com/a/53939059/39396). – Carl G Nov 14 '19 at 19:17
7

Another simple Vanilla solution based on the A1rPun answer (see his fiddle for the jQuery solution, and both are in this one).

It seems that to NOT trigger a single-click handler when the user double-clicks, the single-click handler is necessarily triggered after a delay...

var single = function(e){console.log('single')},
    double = function(e){console.log('double')};

var makeDoubleClick = function(e) {

  var clicks = 0,
      timeout;

  return function (e) {

    clicks++;

    if (clicks == 1) {
      timeout = setTimeout(function () {
        single(e);
        clicks = 0;
      }, 250);
    } else {
      clearTimeout(timeout);
      double(e);
      clicks = 0;
    }
  };
}
document.getElementById('btnVanilla').addEventListener('click', makeDoubleClick(), false);
jeum
  • 1,048
  • 3
  • 13
  • 29
  • 3
    This is indeed the best alternative if you don't want the single click fired :) – A1rPun Mar 23 '16 at 08:33
  • When `event.detail` is available, it is the best way to detect a double-click from the click handler. See [this answer](https://stackoverflow.com/a/53939059/39396). – Carl G Nov 14 '19 at 19:17
7

How to differentiate between single clicks and double clicks on one and the same element?

If you don't need to mix them, you can rely on click and dblclick and each will do the job just fine.

A problem arises when trying to mix them: a dblclick event will actually trigger a click event as well, so you need to determine whether a single click is a "stand-alone" single click, or part of a double click.

In addition: you shouldn't use both click and dblclick on one and the same element:

It is inadvisable to bind handlers to both the click and dblclick events for the same element. The sequence of events triggered varies from browser to browser, with some receiving two click events before the dblclick and others only one. Double-click sensitivity (maximum time between clicks that is detected as a double click) can vary by operating system and browser, and is often user-configurable.
Source: https://api.jquery.com/dblclick/

Now on to the good news:

You can use the event's detail property to detect the number of clicks related to the event. This makes double clicks inside of click fairly easy to detect.

The problem remains of detecting single clicks and whether or not they're part of a double click. For that, we're back to using a timer and setTimeout.

Wrapping it all together, with use of a data attribute (to avoid a global variable) and without the need to count clicks ourselves, we get:

HTML:

<div class="clickit" style="font-size: 200%; margin: 2em; padding: 0.25em; background: orange;">Double click me</div>

<div id="log" style="background: #efefef;"></div>

JavaScript:

<script>
var clickTimeoutID;
$( document ).ready(function() {

    $( '.clickit' ).click( function( event ) {

        if ( event.originalEvent.detail === 1 ) {
            $( '#log' ).append( '(Event:) Single click event received.<br>' );

            /** Is this a true single click or it it a single click that's part of a double click?
             * The only way to find out is to wait it for either a specific amount of time or the `dblclick` event.
             **/
            clickTimeoutID = window.setTimeout(
                    function() {
                        $( '#log' ).append( 'USER BEHAVIOR: Single click detected.<br><br>' );
                    },
                    500 // how much time users have to perform the second click in a double click -- see accessibility note below.
                );

        } else if ( event.originalEvent.detail === 2 ) {
            $( '#log' ).append( '(Event:) Double click event received.<br>' );
            $( '#log' ).append( 'USER BEHAVIOR: Double click detected.<br>' );
            window.clearTimeout( clickTimeoutID ); // it's a dblclick, so cancel the single click behavior.
        } // triple, quadruple, etc. clicks are ignored.

    });

});
</script>

Demo:

JSfiddle


Notes about accessibility and double click speeds:

  • As Wikipedia puts it "The maximum delay required for two consecutive clicks to be interpreted as a double-click is not standardized."
  • No way of detecting the system's double-click speed in the browser.
  • Seems the default is 500 ms and the range 100-900mms on Windows (source)
  • Think of people with disabilities who set, in their OS settings, the double click speed to its slowest.
    • If the system double click speed is slower than our default 500 ms above, both the single- and double-click behaviors will be triggered.
    • Either don't use rely on combined single and double click on one and the same item.
    • Or: add a setting in the options to have the ability to increase the value.

It took a while to find a satisfying solution, I hope this helps!

Fabien Snauwaert
  • 4,995
  • 5
  • 52
  • 70
5

Here's an alternative of jeum's code for an arbitrary number of events:

 var multiClickHandler = function (handlers, delay) {
    var clicks = 0, timeout, delay = delay || 250;
    return function (e) {
      clicks++;
      clearTimeout(timeout);
      timeout = setTimeout(function () {
        if(handlers[clicks]) handlers[clicks](e);
        clicks = 0;
      }, delay);
    };
  }

  cy.on('click', 'node', multiClickHandler({
    1: function(e){console.log('single clicked ', e.cyTarget.id())},
    2: function(e){console.log('double clicked ', e.cyTarget.id())},
    3: function(e){console.log('triple clicked ', e.cyTarget.id())},
    4: function(e){console.log('quadro clicked ', e.cyTarget.id())},
    // ...
  }, 300));

Needed this for a cytoscape.js app.

nex
  • 685
  • 1
  • 9
  • 21
  • Nice! we can also declare a new variable inside the returned function and assign it with `this`, which is the clicked element, and pass it to the handler (alongside `e` or instead of it). – OfirD Jul 27 '17 at 17:08
4

Use the excellent jQuery Sparkle plugin. The plugin gives you the option to detect first and last click. You can use it to differentiate between click and dblclick by detecting if another click was followed by the first click.

Check it out at http://balupton.com/sandbox/jquery-sparkle/demo/

Hussein
  • 42,480
  • 25
  • 113
  • 143
3

I wrote a simple jQuery plugin that lets you use a custom 'singleclick' event to differentiate a single-click from a double-click:

https://github.com/omriyariv/jquery-singleclick

$('#someDiv').on('singleclick', function(e) {
    // The event will be fired with a small delay.
    console.log('This is certainly a single-click');
}
omriyariv
  • 151
  • 5
2

I like to avoid jquery (and other 90-140k libs), and as noted browsers handle onclick first, so here is what I did on a website I created (this example also covers getting a clicked location local x y )

clicksNow-0; //global js, owell

function notify2(e, right) {  // called from onclick= and oncontextmenu= (rc)
var x,y,xx,yy;
var ele = document.getElementById('wrap');  
    // offset fixed parent for local win x y
var xxx= ele.offsetLeft;
var yyy= ele.offsetTop;

//NScape
if (document.layers || document.getElementById&&!document.all) {
    xx= e.pageX;
    yy= e.pageY;
} else {
    xx= e.clientX;
    yy= e.clientY;
}
x=xx-xxx;
y=yy-yyy;

clicksNow++;
    // 200 (2/10ths a sec) is about a low as i seem to be able to go
setTimeout( "processClick( " + right + " , " + x + " , " + y + ")", 200);
}

function processClick(right, x, y) {
if (clicksNow==0) return; // already processed as dblclick
if (clicksNow==2) alert('dbl');
clicksNow=0;
    ... handle, etc ...
}

hope that helps

Andrew Barber
  • 39,603
  • 20
  • 94
  • 123
dako
  • 29
  • 1
1

Based on Adrien Schuler (thank you so much!!!) answer, for Datatables.net and for many uses, here is a modification:

Function

/**
 * For handle click and single click in child's objects
 * @param {any} selector Parents selector, like 'tr'
 * @param {any} single_click_callback Callback for single click
 * @param {any} double_click_callback Callback for dblclick
 * @param {any} timeout Timeout, optional, 300 by default
 */
jQuery.fn.single_double_click = function (selector, single_click_callback, double_click_callback, timeout) {
    return this.each(function () {
        let clicks = 0;
        jQuery(this).on('click', selector, function (event) {
            let self = this;
            clicks++;
            if (clicks == 1) {
                setTimeout(function () {
                    if (clicks == 1) {
                        single_click_callback.call(self, event);
                    } else {
                        double_click_callback.call(self, event);
                    }
                    clicks = 0;
                }, timeout || 300);
            }
        });
    });
}

Use

$("#MyTableId").single_double_click('tr',
            function () {   //  Click
                let row = MyTable.row(this);
                let id = row.id();
                let data = row.data();
                console.log("Click in "+id+" "+data);
            },
            function () {   //  DBLClick
                let row = MyTable.row(this);
                let id = row.id();
                let data = row.data();
                console.log("DBLClick in "+id+" "+data);
            }
        );
Dani
  • 1,825
  • 2
  • 15
  • 29
1
let clickTimes = 0;
let timer = null;
roundBox.click = function (e) {
  clearTimeout(timer);
  timer = setTimeout(() => { // 单击事件
    console.log("single click");
  }, 600);
  clickTimes++;

  if (clickTimes == 2) { // 双击
    clearTimeout(timer);
    clickTimes = 0;
    console.log("double click");
    toggleExpanded(id);
  }
}
Xu Jingli
  • 11
  • 1
0

this worked for me–

var clicked=0;
function chkBtnClcked(evnt) {
    clicked++;
    // wait to see if dblclick
    if (clicked===1) {
        setTimeout(function() {
            clicked=0;
            .
            .
        }, 300); // test for another click within 300ms
    }
    if (clicked===2) {
        stopTimer=setInterval(function() {
            clicked=0;
            .
            .
        }, 30*1000); // refresh every 30 seconds
    }
}

usage–

<div id="cloneimages" style="position: fixed;" onclick="chkBtnClcked(evnt)"  title="Click for next pic; double-click for slide show"></div>
cneeds
  • 319
  • 3
  • 13
0

Just posting the native HTML answer just in case the need is to be easy and HTML.

<p ondblclick="myFunction()" id = 'id'>Double-click me</p>

This of course has native Jquery options. ie... $('#id').attr('ondblclick',function(){...}) or, as stated previously, $('#id').dblclick(function(){...});

JSG
  • 390
  • 1
  • 4
  • 13
0

I know this is old, but below is a JS only example of a basic loop counter with a single timer to determine a single vs double click. Hopefully this helps someone.

var count = 0;
var ele = document.getElementById("my_id");
ele.addEventListener('click', handleSingleDoubleClick, false); 

function handleSingleDoubleClick()
{
  if(!count) setTimeout(TimerFcn, 400); // 400 ms click delay
  count += 1;
}
function TimerFcn() 
{
  if(count > 1) console.log('you double clicked!')
  else console.log('you single clicked')
  count = 0;
}
Tim
  • 1,105
  • 13
  • 14
0

Try this code

let click = 0;
element.onclick = (event) => {
  click++;
  console.log(click);
  setTimeout(() => {
    click = 0;
  }, 300);
  if (click === 2) {
    console.log("double Click");
    click = 0;
    console.log(click);
  }
};
Behemoth
  • 5,389
  • 4
  • 16
  • 40
0

If you want to distinguish between a single and double click, the event handler of the single click has to wait until it is proven, that the single click is not the beginning of a double click. This makes single clicks lagging. The example shows this.

var distinguish = (() => {
  var target = null;
  var timeout = null;
  return (element, action) => {
    element.addEventListener ('click', e => {
      if (e.target === target) {
        clearTimeout (timeout);
        target = null;
        timeout = null;
        action ('double');
      } else {
        target = e.target;
        timeout = setTimeout (() => {
          target = null;
          timeout = null;
          action ('single');
        }, 500);
      }
    });
  };
})();

var button = document.getElementById ('button');

distinguish (button, kind => console.log (kind + ' click'));
<input id="button" type="button" value="click">
ceving
  • 21,900
  • 13
  • 104
  • 178
0

Pure JS, to truly differentiate single- vs double-click, (e.g. not triggering both at the same time). I'm using this combination of the native event.detail and a custom delay, to prevent the single-click from firing, if it gets cancelled by a double-click. This approach is also very performance friendly, as it doesn't start a new timer every time we click in quick succession.

The only minor thing (as with some of the other solutions too), is that it may still fire both events, if the user double-clicks very very slowly. This can be prevented by highering the delay, but that would make single-clicking feel even more laggy.

Also there is a lot of differences in the suggested answers as to how they handle quick multi-clicking. So to make things clear, here is what happens in every consecutive click with this approach:

  1. triggers a slightly delayed single-click, if it isn't cancelled by a doubleclick
  2. triggers double-click
  3. nothing
  4. triggers double-click
  5. nothing

...(every 2nd click is a doubleclick, which feels very natural)

I included a snippet so you can test it for yourself.

document.querySelector('button').addEventListener('click', single_or_double);

let isSingleClick; // flag to allow or cancel single clicks 

function single_or_double(){
  if (isSingleClick = event.detail == 1){ //check for a singleclick and store flag globally at the same time
    setTimeout(() => {
      if(isSingleClick){ //check if the flag is still set after the delay
        console.log("single");
      }
    }, 200); // singleclick delay in milliseconds
  }
  else if (event.detail == 2) {
    console.log("double");
  }
}
<button>Single OR Double-Click</button>
Foxcode
  • 1,279
  • 11
  • 10