How can I write an onclick handler that does one thing for regular clicks and a different thing for shift-clicks?
The shiftKey property returns a Boolean value that indicates whether or not the "SHIFT" key was pressed when a key event was triggered.
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 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.
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>
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>
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