Question

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

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

 45  27481  45
1 Jan 1970

Solution

 77

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>

2009-04-06

Solution

 7

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>
2013-08-06