How to Differentiate Single Click Event and Double Click Event

How to differentiate single click event and double click event?

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/

Javascript how to distinguish between mouseDown, click and doubleClick events

dblclick event fires after two click events and after two pairs of mousedown and mouseup events.

Usually, we see such a case when for example selecting/focusing a file by a single click and then executing a file by double click. There is no harm in selecting the same file multiple times.

If you need to distinguish these two events, you can postpone single click handling until you are sure it is not part of the double click, but this will add a delay in handling.

let clicks = 0;
let clickTimer = 0;
const dblClickTimeSpan = 300;

const clickHandler = (e) => {
clicks++;
if(clicks === 1) {
clickTimer = setTimeout(()=>{
clicks = 0;
// handle single click, now we are sure it is not a bouble click
console.log('Single Click.')
}, dblClickTimeSpan);
}
if(clicks === 2) {
// it is the second click in double-click event
clearTimeout(clickTimer);
clicks = 0;
}
}

myButton.addEventListener('click', clickHandler);
myButton.addEventListener('dblclick', (e) => console.log('Double Click.'));
<button id="myButton">Button</button>

Single click and Double click on the same element, not working; Javascript

Update:

Try passing a function clicks() to your event listener like so:

onEvent("image2", "click", clicks);

Function clicks() will check if there was a single or double click based on setTimeout function. You can adjust setTimeout via timeout variable and of course you need clickCount variable declared outside clicks() function.


Pure js approach

Try adding two event listeners. Less code, much cleaner. Check this working example.

var selector = document.getElementById('codeorg');selector.addEventListener('click', clicks);

// Global Scope variable we need thisvar clickCount = 0;// Our Timeout, modify it if you needvar timeout = 500;// Copy this function and it should workfunction clicks() { // We modify clickCount variable here to check how many clicks there was clickCount++; if (clickCount == 1) { setTimeout(function(){ if(clickCount == 1) { console.log('singleClick'); // Single click code, or invoke a function } else { console.log('double click'); // Double click code, or invoke a function } clickCount = 0; }, timeout || 300); }}

// Not important for your needs - pure JS stuffvar button = document.getElementById('button');
button.addEventListener('click', singleClick);button.addEventListener('dblclick', doubleClick);
function singleClick() { //console.log('single click');}
function doubleClick() { console.log('double click');}
#codeorg {  margin-bottom: 100px;}
<h2>Double Click</h2>
<button id="button">Click me</button>

<hr><hr>

<h2>Double click or Single Click</h2>
<button id="codeorg">Click me</button>

js differ click and double click

If you dont want to execute the single click at all in case of double, you can use a timeout like you did. You just have to reset the counter and the timeout properly. You do not reset el.cdblc on your last empty else.

Be aware, that this delays normal clicks.

/* dblclick differ click 
takes two functions as param and one element
to bind the event listener on
*/
function cdblclick(click, dblclick, el){
//REM: Storing the values in an object instead of own element properties
let tObject = {
Clicks: 0,
onClick: click,
onDblClick: dblclick
};

//el.cooled = true;
el.addEventListener('click', function(object){
object.Clicks += 1;

//REM: Starting the click..
if(object.Clicks === 1){
object.Timeout = window.setTimeout(function(){
//REM: Execute click if not stopped
if(typeof object.onClick == 'function'){
object.onClick()
};

//REM: Resetting the click count
object.Clicks = 0

/*if(!el.cdblc){el.cdblc = 0}
el.cdblc++;
if(el.cdblc === 1){
setTimeout(function(){
if(!el.doubled){
console.log('click')
// click();
el.cdblc = 0;
el.cooled = true;
el.doubled = false;
}
*/
}.bind(this, object), 300)
}
//REM: Unless we have triple clicks, there is only double left
else{
//REM: Cancel the single click
window.clearTimeout(object.Timeout);

//REM: Execute double click
if(typeof object.onDblClick === 'function'){
object.onDblClick()
};

//REM: Resetting the click count
object.Clicks = 0

/*
console.log('double')
// dblclick();
el.doubled = true;
el.cdblc = 0;
el.cooled = true;
*/
}
}.bind(el, tObject))
};

document.querySelector('b').onclick = cdblclick(
function(){console.log('onclick')},
function(){console.log('ondblclick')},
document.body
);
<b>Click me</b>

Distinguish between a single click and a double click in Java

Sometime it prints out " and it's a single click!" 2 times . It should print out " and it's a double click!").

That is normal. A double click only happens if you click twice within the specified time interval. So sometimes if you don't click fast enough you will get two single clicks in a row.

Integer timerinterval = (Integer) Toolkit.getDefaultToolkit().getDesktopProperty("awt.multiClickInterval"); 

The above line of code determines how fast the double click must be.

For what its worth here is some code I have used to do the same thing. Don't know if its any better or worse than the code you have:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

public class ClickListener extends MouseAdapter implements ActionListener
{
private final static int clickInterval = (Integer)Toolkit.getDefaultToolkit().
getDesktopProperty("awt.multiClickInterval");

MouseEvent lastEvent;
Timer timer;

public ClickListener()
{
this(clickInterval);
}

public ClickListener(int delay)
{
timer = new Timer( delay, this);
}

public void mouseClicked (MouseEvent e)
{
if (e.getClickCount() > 2) return;

lastEvent = e;

if (timer.isRunning())
{
timer.stop();
doubleClick( lastEvent );
}
else
{
timer.restart();
}
}

public void actionPerformed(ActionEvent e)
{
timer.stop();
singleClick( lastEvent );
}

public void singleClick(MouseEvent e) {}
public void doubleClick(MouseEvent e) {}

public static void main(String[] args)
{
JFrame frame = new JFrame( "Double Click Test" );
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.addMouseListener( new ClickListener()
{
public void singleClick(MouseEvent e)
{
System.out.println("single");
}

public void doubleClick(MouseEvent e)
{
System.out.println("double");
}
});
frame.setSize(200, 200);
frame.setVisible(true);
}
}

Distinguish between single and double click events in Qt

You can find answer in the thread titled Double Click Capturing on QtCentre forum;

You could have a timer. Start the
timer in the releaseEvent handler and
make sure the timeout is long enough
to handle the double click first.
Then, in the double click event
handler you can stop the timer and
prevent it from firing. If a double
click handler is not triggered, the
timer will timeout and call a slot of
your choice, where you can handle the
single click. This is of course a
nasty hack, but has a chance to work.

wysota



Related Topics



Leave a reply



Submit