I recently needed to detect if the shift key was pressed when the user clicked on a link. The idea is when they click do “X”, but when they hold shift and click do “Y”. Because I have seen it a few times in various web apps (gmail), I new it should be trivial. The trouble was I didn’t exactly know how to do it, so I am going to go over my thought process.

The first thing I did was capture a click event on a link. Here’s the link:

shift click for something fancy

Here is the prototype event observation:

$(’detectShift’).observe(’click’,shiftFunction);

Here is where it starts to get interesting. I first made an assumption that what I was looking for would be obtained using the event object. After making an assumption like that, I need to test my theory immediately. The second thing I did was determine the attributes and functions of the event object. This was done quite simply by taking advantage of the flexibility of javascript. I converted the event object to a prototype Hash then called keys on it.

function shiftFunction(event) { Event.stop(event); console.log($H(event).keys()); }

In case you were wondering, the “console.log” is a firebug logging statement, similar to alert. The shiftFunction logs all the attributes and functions of event[1]. The attribute I was looking for turned out to be simple, shiftKey. I altered my function to take advantage of this newly found attribute.

function shiftFunction(event) { Event.stop(event); if(event.shiftKey) { console.log(”shift key was pressed”); } else { console.log(”regular click”); } }

I am sure I could have figured this out with a quick google query, but it is nice to be self reliant. This was a trivial example, but the same technique can be applied to any object in javascript.

1: Because some of them may not be cross browser compatible, do not use them with out testing on important browsers.

Post Information

Tags:

We're Reading

Feeds/Syndication

3 Responses to “Shift Key Detection”

Leave a Reply