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

JavascriptJquery

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

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()

Solution 2 - Javascript

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


}

Solution 3 - Javascript

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

Solution 4 - Javascript

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>

Solution 5 - Javascript

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.

Solution 6 - Javascript

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

Solution 7 - Javascript

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.

Solution 8 - Javascript

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>

Solution 9 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBrownChiLDView Question on Stackoverflow
Solution 1 - JavascriptBjörn RobergView Answer on Stackoverflow
Solution 2 - JavascriptMasNotsramView Answer on Stackoverflow
Solution 3 - JavascriptAndrewView Answer on Stackoverflow
Solution 4 - JavascriptKranthi SamalaView Answer on Stackoverflow
Solution 5 - JavascriptFerhat KOÇERView Answer on Stackoverflow
Solution 6 - JavascriptArnelle BalaneView Answer on Stackoverflow
Solution 7 - JavascriptDeezView Answer on Stackoverflow
Solution 8 - JavascriptArun Prasad E SView Answer on Stackoverflow
Solution 9 - JavascriptjazzView Answer on Stackoverflow