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.
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.
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.
To capture the right-click event in JavaScript, we can listen for the contextmenu event. el. addEventListener( "contextmenu", (ev) => { ev. preventDefault(); //... }, false );
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With