85

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 code is 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.

starball
  • 20,030
  • 7
  • 43
  • 238
BrownChiLD
  • 3,545
  • 9
  • 43
  • 61

9 Answers9

127

In your handler, check the window.event object for the property ctrlKey as such:

function selectMe(){
    if (window.event.ctrlKey) {
        //ctrl was held down during the click
    }
}

UPDATE: the above solution depends on a proprietary property on the window object, which perhaps should not be counted on to exist in all browsers. Luckily, we now have a working draft that takes care of our needs, and according to MDN, it is widely supported. Example:

HTML

<span onclick="handler(event)">Click me</span>

JS

function handler(ev) {
  console.log('CTRL pressed during click:', ev.ctrlKey);
}

The same applies for keyboard events

See also KeyboardEvent.getModifierState()

Björn Roberg
  • 2,275
  • 2
  • 15
  • 15
  • 2
    apparently, `window.event` is proprietary to IE https://developer.mozilla.org/en-US/docs/Web/API/Window/event, but there's a working draft https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/ctrlKey that seems to be widely supported, which seems like a better API, since the property is attached to the event sent to the handler. – Björn Roberg Sep 23 '15 at 07:43
  • Works also on chrome, but indeed not on Firefox. Meh. :-/ – Soullivaneuh Jul 07 '16 at 15:03
  • 3
    Just a note: this works fine for a PC; on a Mac, for many applications, you may want to test for window.event.metaKey, which tells you whether the Command key has been pressed. – xgretsch Aug 21 '17 at 11:21
54

2021 UPDATE: There are better ways to do this now. Please be sure to check out the other answers

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


}
MasNotsram
  • 2,105
  • 18
  • 28
  • 1
    thanks.. this makes sense.. atleast i need not change my existing codes too much. – BrownChiLD Apr 25 '13 at 07:32
  • At last I can implement the backdoor to my personal files as an homage The Net: http://jsfiddle.net/4DdCs/ (I'm 92% kidding) – Jason Sperske Apr 04 '14 at 18:40
  • What If i press Crtl, then release it and then click the link!? It still thinks I am pressing it – DavidDunham Jul 21 '16 at 07:48
  • 4
    The code should look more like this I think: ```$(document).keydown(($event) => { if($event.which === 17) { this.ctrlIsPressed = true; } }); $(document).keyup(($event) => { if($event.which === 17) { this.ctrlIsPressed = false; } });``` – Karvapallo Aug 24 '16 at 16:04
  • 2
    There are better ways to do this now, see [this answer](http://stackoverflow.com/a/16190632/542251) – Liam Nov 18 '16 at 15:01
44

Because it's been a several years since this question was first asked, the other answers are outdated or incomplete.

Here's the code for a modern implementation using jQuery:

$( 'div#1' ).on( 'click', function( event ) {
    if ( event.ctrlKey ) {
        //is ctrl + click
    } else {
        //normal click
    }
} );

As for detecting right-clicks, this was correctly provided by another user but I'll list it here just to have everything in one place.

$( 'div#1' ).on( 'contextmenu', function( event ) {
    // right-click handler
} ) ;
Andrew
  • 569
  • 4
  • 5
  • 1
    But doesn't help if we need to check for the ctrl key within some other method or event handler – Andrew Oct 04 '18 at 19:15
16

When there is a mouse click ctrlKey is event attribute which can be accessed as e.ctrlKey. Look down for example

$("xyz").click(function(e)){
  if(e.ctrlKey){
    //if ctrl key is pressed
  }
  else{
    // if ctrl key is not pressed
  }
}

note: https://www.w3schools.com/jsref/event_key_keycode.asp

Kranthi Samala
  • 171
  • 1
  • 6
  • 1
    Perfect! Note that `event.ctrlKey` is not jQuery specific. You can also use it in onclick-Attribute of an element: `` – mihca Jan 05 '21 at 12:40
6

Try this code,

$('#1').on('mousedown',function(e) {
   if (e.button==0 && e.ctrlKey) {
       alert('is Left Click');
   } else if (e.button==2 && e.ctrlKey){
       alert('is Right Click');
   }
});

Sorry I added e.ctrlKey.

Ferhat KOÇER
  • 3,890
  • 1
  • 26
  • 26
4

Try this:

var control = false;
$(document).on('keyup keydown', function(e) {
  control = e.ctrlKey;
});

$('div#1').on('click', function() {
  if (control) {
    // control-click
  } else {
    // single-click
  }
});

And the right-click triggers a contextmenu event, so:

$('div#1').on('contextmenu', function() {
  // right-click handler
})
Arnelle Balane
  • 5,437
  • 1
  • 26
  • 32
  • 1
    Assuming that control is released on a keyup event is a mistake, if I hold control and tap shift nothing happens, but now you don't register the ctrl+click event correctly. Check which key is released to ensure it matches. – scragar Feb 24 '15 at 17:07
  • @scragar thanks for catching that, i'll update it now :) – Arnelle Balane Feb 24 '15 at 19:12
0

You cannot detect if a key is down after it's been pressed. You can only monitor key events in js. In your case I'd suggest changing onclick with a key press event and then detecting if it's the control key by event keycode, and then you can add your click event.

Deez
  • 849
  • 2
  • 9
  • 28
0

From above only , just edited so it works right away

<script>
    var control = false;
    $(document).on('keyup keydown', function (e) {
        control = e.ctrlKey;
    });

    $(function () {
        $('#1x').on('click', function () {
            if (control) {
                // control-click
                alert("Control+Click");
            } else {
                // single-click
                alert("Single Click");
            }
        });
    }); 

</script>
<p id="1x">Click me</p>
Arun Prasad E S
  • 9,489
  • 8
  • 74
  • 87
-2

pure javascript:

var ctrlKeyCode = 17;
var cntrlIsPressed = false;

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

document.addEventListener('keyup', function(){
    if(event.which=="17")
        cntrlIsPressed = true;
});



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