This is a very old question. gilly3's answer is valid only if we have at hand an event object of type KeyboardEvent passed as a function argument. How to detect the current control key state if we have not event object available such as in this function?
function testModifierKey() { // have I some modifier key hold down at this running time? }
I found the solution after a long search from https://gist.github.com/spikebrehm/3747378 of spikebrehm. his solution is tracing the modifier key state at any time using jQuery with a global variable.
The global variable window.modifierKey can be used in any circonstance without requiring event object.
function testModifierKey() { // have I have some modifier key hold down at this executing time? if(window.modifierKey) { console.log("Some modifier key among shift, ctrl, alt key is currently down."); // do something at this condition... for example, delete item without confirmation. } else { console.log("No modifier key is currently down."); // do something at other condition... for example, delete this item from shopping cart with confirmation. } }
Here is his script to load in your HTML document:
// source: https://gist.github.com/spikebrehm/3747378 // modifierKey used to check if cmd+click, shift+click, etc. !function($, global){ var $doc = $(document); var keys; global.modifierKey = false; global.keys = keys = { 'UP': 38, 'DOWN': 40, 'LEFT': 37, 'RIGHT': 39, 'RETURN': 13, 'ESCAPE': 27, 'BACKSPACE': 8, 'SPACE': 32 }; // borrowed from Galleria.js var keyboard = { map: {}, bound: false, press: function(e) { var key = e.keyCode || e.which; if ( key in keyboard.map && typeof keyboard.map[key] === 'function' ) { keyboard.map[key].call(self, e); } }, attach: function(map){ var key, up; for(key in map) { if (map.hasOwnProperty(key)) { up = key.toUpperCase(); if (up in keyboard.keys) { keyboard.map[keyboard.keys[up]] = map[key]; } else { keyboard.map[up] = map[key]; } } } if (!keyboard.bound) { keyboard.bound = true; $doc.bind('keydown', keyboard.press); } }, detach: function() { keyboard.bound = false; keyboard.map = {}; $doc.unbind('keydown', keyboard.press); } }; $doc.keydown(function(e) { var key = e.keyCode || e.which; if (key === 16 || key === 91 || key === 18 || key === 17) { modifierKey = true; } else { modifierKey = false; } }); $doc.keyup(function(e) { modifierKey = false; }); }(jQuery, window);
eventobject? You can test theevent.ctrlKeyproperty to see if the ctrl key was down when the key event was generated, and also test for thekeyCodecorresponding to the A key.