Created
          February 17, 2011 15:21 
        
      - 
      
- 
        Save sunny/831913 to your computer and use it in GitHub Desktop. 
    SingleKeyDown jQuery plugin
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | /** | |
| * SingleKeyDown | |
| * | |
| * Returns when a key has been pressed but does not trigger | |
| * if control or command is beeing pressed. | |
| * | |
| * Also, adds the name of the key in the event under the | |
| * `keyName` option. Includes special names for the keys | |
| * left & right. | |
| * | |
| * Example: | |
| * $(document).singleKeyDown(function(e) { | |
| * if (e.keyName == 'l') | |
| * return alert('pressed L and not command L') | |
| * }) | |
| **/ | |
| $.fn.singleKeyDown = function(callback) { | |
| var upKeys = {} | |
| function keyName(code) { | |
| switch (code) { | |
| case 17: return 'control' | |
| case 224: return 'command' | |
| case 37: return 'left' | |
| case 39: return 'right' | |
| default: return String.fromCharCode(code) | |
| } | |
| } | |
| $(this).keydown(function(e) { | |
| e.keyName = keyName(e.keyCode) | |
| if (e.keyName == 'control' || e.keyName == 'command') | |
| upKeys[e.keyName] = true | |
| else if (!upKeys.control && !upKeys.command) | |
| return callback.call(this, e) | |
| }).keyup(function(e) { | |
| e.keyName = keyName(e.keyCode) | |
| if (e.keyName == 'control' || e.keyName == 'command') | |
| upKeys[e.keyName] = false | |
| }) | |
| } | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment