views:

1173

answers:

1

I've searched a good deal, and can't seem to find a satisfactory solution. I hope someone can help.

While I am using jQuery, I am also writing many thousands of lines of Javascript. So a "pure" javascript solution is just fine.

I'm trying to determine if the control key is physically held down on a mouseup event. That's it; there are no other preconditions. Does anyone know how to do this reliably, cross-browser?

I've tried storing this in a state variable by noting when the key is pressed and released:

// BEGIN store control key status in hash_state
$().bind('keydown','ctrl',function( arg_obj_e ){
  hash_state.sw_ctrldn = true;
  console.debug( hash_state.sw_ctrldn );
});
$().bind('keyup','ctrl',function( arg_obj_e ){
  hash_state.sw_ctrldn = false;
  console.debug( hash_state.sw_ctrldn );
});
// END store control key status in hash_state

However, this really doesn't work. If you test this using firebug and watch the console, you will see that auto-repeat seems to happen, and the value toggles.

I inspected the mouseup event to see if there is anything useful there, but to no avail:

var debugEvent = function( arg_obj_e ){
  var str = '';
  for ( var attr in arg_obj_e ){
    str += attr + ': ' + arg_obj_e[attr] + '\n';
  }
  console.debug(str);
}

Any help would be appreciated.

+5  A: 

You can use the event.ctrlKey property.

$(function(){
  $('#elementId').mouseup(function(e){
    var isCtrlPressed = e.ctrlKey;
    // true or false whether ctrl is pressed or not 
  });
});

Check a running example here.

CMS
Wow, I was looking for that property during the event debug, and must have missed it. Thank you! Works like a charm on FF3; now to see about IE.
Michael Mikowski
ps thank you for the demo, its very much appreciated.
Michael Mikowski
You're welcome Michael, these key modifiers (shiftKey, ctrlKey, altKey) were introduced on the *DOM Level 2* standard (http://is.gd/1Vryp) in the late year 2000, and is supported since IE6.
CMS
Even better! I want to use both shiftKey and altKey in my app as well. I just found that ctrl-mousewheel in firefox defaults to text zooming, which could case my users fits. Maybe better to use one of the other keys :)These properties must "spring to life" when queried, it seems, because just iterating over the attributes of the event object gave me nothing, IIRC.Again, thanks a lot. Saved e much trouble.
Michael Mikowski