Tutorial :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?


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>


The event fired from the DOM ought to contain a shiftKey (or equivalent) property indicating the state of the shift key when the event was fired; see, e.g. https://developer.mozilla.org/en/DOM/event.shiftKey for an example.

If you're using a JavaScript/DOM wrapping library such as YUI, Prototype or jQuery, any differences in implementation ought not to be an issue.


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>  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »