Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 230
BrownChiLD Avatar asked Apr 24 '13 11:04

BrownChiLD


People also ask

How do I find Ctrl click?

The mouseEvent ctrlKey property is used to define whether the ctrl key is pressed or not. It is a boolean value. When ctrl key is pressed then on click of the mouse buttons it returns true and if it is not pressed then it returns false.

How do you check if a div is clicked JavaScript?

To check if an element was clicked, add a click event listener to the element, e.g. button. addEventListener('click', function handleClick() {}) . The click event is dispatched every time the element is clicked.

How can I capture the right click event in JavaScript?

To capture the right-click event in JavaScript, we can listen for the contextmenu event. el. addEventListener( "contextmenu", (ev) => { ev. preventDefault(); //... }, false );

What is click () method?

The click() method simulates a mouse-click on an element. This method can be used to execute a click on an element as if the user manually clicked on it.


1 Answers

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

like image 52
Björn Roberg Avatar answered Oct 12 '22 17:10

Björn Roberg