166

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

5

22 Answers 22

115

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

5
  • The best answer :) Jan 1, 2019 at 8:09
  • 27
    In the case of double clicks, a single click (where event.detail === 1) will still trigger. See my fiddle or this comment on this thread. Jan 31, 2019 at 14:37
  • 2
    You still need a timer on that first click to not fire. Check my answer below stackoverflow.com/questions/5497073/…
    – user670839
    Feb 11, 2020 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 5, 2020 at 20:43
  • evt.detail will also track additional clicks beyond a double-click (e.g. triple-click). Jun 20, 2020 at 6:26
89

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.

4
  • 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, 2017 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, 2018 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.
    – Carl G
    Nov 14, 2019 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 9, 2020 at 14:54
80

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/

5
  • 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, 2013 at 15:52
  • 1
    Yeah I think you're right, dblclick is definitively the way to go today. jQuery also handles this event: api.jquery.com/dblclick Apr 23, 2013 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. Apr 23, 2013 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.
    – Carl G
    Nov 14, 2019 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: playcode.io/492022
    – BernhardS
    Jan 31, 2020 at 10:52
43

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>

2
  • Solved my problem. Only problem is it affected my performance a bit but that very negligible. Nov 26, 2021 at 13:09
  • Sometimes fires a single click before the double one.
    – quilkin
    Feb 6 at 13:49
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>
4
  • 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 3, 2013 at 9: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, 2014 at 15:16
  • using el.dataset.dblclick would be a nicer way of doing this now.
    – WORMSS
    Feb 25, 2016 at 9:32
  • When event.detail is available, it is the best way to detect a double-click from the click handler. See this answer.
    – Carl G
    Nov 14, 2019 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.

1
  • 2
    When event.detail is available, it is the best way to detect a double-click from the click handler. See this answer.
    – Carl G
    Nov 14, 2019 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')
});
0
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

8
  • 2
    The code above and the 'Vanilla' version of your fiddle don't work ... here is a fixed Vanilla version : jsfiddle.net/jeum/cpbwx5vr/19
    – jeum
    Mar 22, 2016 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, 2016 at 12:31
  • Fist I have modified my version (removed double closure), please try the new one : 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, 2016 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, 2016 at 15:47
  • 1
    Yes error again, so this version respond to the main question : 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, 2016 at 16:07
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);
2
  • 3
    This is indeed the best alternative if you don't want the single click fired :)
    – A1rPun
    Mar 23, 2016 at 8:33
  • When event.detail is available, it is the best way to detect a double-click from the click handler. See this answer.
    – Carl G
    Nov 14, 2019 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!

0
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.

1
  • 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, 2017 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/

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');
}
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

2
  • 2
    The URL to your game is not required to understand your answer at all. I am removing it so that this post is not seen as an attempt to spam. Nov 19, 2012 at 20:14
  • 1
    the only minus, 200 is magic constant and can drastically vary from user's mouse settings in OS May 6, 2013 at 9:48
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);
            }
        );
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);
  }
}
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>
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(){...});

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;
}
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">

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>

-1

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);
  }
};

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.