Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In an onclick handler, how can I detect whether shift was pressed?

Tags:

javascript

How can I write an onclick handler that does one thing for regular clicks and a different thing for shift-clicks?

like image 702
mike Avatar asked Apr 06 '09 21:04

mike


People also ask

How do you know if shiftKey is pressed?

The shiftKey property returns a Boolean value that indicates whether or not the "SHIFT" key was pressed when a key event was triggered.

Is Shift pressed?

The Shift key is a keyboard modifier key that allows users to type a single capital letter and change the top number keys to a symbol. For example, pressing and holding the Shift while pressing A generates a capital "A" and pressing the Shift and the number 1 creates an exclamation mark on US keyboards.

What does the onclick event handler do?

What is the onClick handler in React? The React onClick event handler enables you to call a function and trigger an action when a user clicks an element, such as a button, in your app. Event names are written in camelCase, so the onclick event is written as onClick in a React app.


2 Answers

You can look at the click event's shiftKey property.

window.addEventListener("click",    function(e) {      if (e.shiftKey) console.log("Shift, yay!");    },    false);
<p>Click in here somewhere, then shift-click.</p>
like image 108
AKX Avatar answered Sep 20 '22 23:09

AKX


You need to make sure you pass event as a parameter to your onclick function. You can pass other parameters as well.

<html> <head>     <script type="text/javascript">         function doSomething(event, chkbox)         {             if (event.shiftKey)                 alert('Shift key was pressed while picking ' + chkbox.value);             else                 alert('You picked ' + chkbox.value);         }     </script> </head> <body>     <h3>Pick a Color</h3>     <input type="radio" name="myColors" onclick="doSomething(event, this)" value="Red" /> Red<br/>     <input type="radio" name="myColors" onclick="doSomething(event, this)" value="Green" /> Green<br/>     <input type="radio" name="myColors" onclick="doSomething(event, this)" value="Blue" /> Blue<br/> </body> </html> 
like image 36
Ryan Avatar answered Sep 23 '22 23:09

Ryan