Skip to content Skip to sidebar Skip to footer

Check Which Mouse Button Was Pressed And If Its A Double Click?

I have a canvas which listens for mouse down event... but I wanted to make it more detailed by listening on the buttons and if they were double clicks or not. I have this: canvas.

Solution 1:

I don't think that the 'mousedown' event is able to anticipate whether or not a second mouse click will occur. You'll have to bind to both 'click' and 'dblclick' and then override the behavior if a double-click occurred...

Inside the handler, the e.button property tells you which button was clicked:

0 => left
1 => middle
2 => right

This works for me:

var dblclick;
var timeout;

$( document ).on( 'click', function ( e ) {
    if ( !timeout ) {
        timeout = setTimeout( function () {
            timeout = 0;           
            handler( dblclick ? 'dblclick' : 'click' );
            dblclick = false;
        }, 200 );
    }
});

$( document ).on( 'dblclick', function ( e ) {
    dblclick = true;
});

// this function receives either 'click' or 'dblclick'// and performs the corresponding actionfunctionhandler ( type ) {
    alert( type );
}

Live demo:http://jsfiddle.net/f73tY/1/

I use a delay value of 200. I have found that (at least on my machine) a value of 100 does not detect a double-click.

Solution 2:

Use click/dblclick:

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

button.ondblclick = function() {
    doubleClick = true;
};​

You can even add an normalClick = false then use that information in your code.

Post a Comment for "Check Which Mouse Button Was Pressed And If Its A Double Click?"