BrownChiLD BrownChiLD - 5 months ago 23
jQuery Question

How to detect control+click in Javascript from an onclick div attribute?

I need to know if the user is clicking or CONTROL CLICKING a div element..
i have seen examples on how to do it using event listeners.. but my codes are already set in place, and is using an on-element onclick method..

HTML

<div id='1' onclick='selectMe()'>blah</div>


JS

function selectMe(){
//determine if this is a single click, or a cntrol click
}


...also would love to know if it was a left or right mouse button click.

Answer

I'd recommend using JQuery's keyup and keydown methods on the document, as it normalizes the event codes, to make one solution crossbrowser.

For the right click, you can use oncontextmenu, however beware it can be buggy in IE8. See a chart of compatibility here:

http://www.quirksmode.org/dom/events/contextmenu.html

<p onclick="selectMe(1)" oncontextmenu="selectMe(2)">Click me</p>

$(document).keydown(function(event){
    if(event.which=="17")
        cntrlIsPressed = true;
});

$(document).keyup(function(){
    cntrlIsPressed = false;
});

var cntrlIsPressed = false;


function selectMe(mouseButton)
{
    if(cntrlIsPressed)
    {
        switch(mouseButton)
        {
            case 1:
                alert("Cntrl +  left click");
                break;
            case 2:
                alert("Cntrl + right click");
                break;
            default:
                break;
        }
    }


}
Comments