0

I am trying to create a look up table ( as i have large number of keys to handle) for handling my keys functionality. So far i have been able to handle single key presses as shown below:

(function(){
       document.body.addEventListener('keydown',keysHandler,false); 
       var keyLookUp = {37:leftKey,39:rightKey,40:DownKey...etc}

       function keysHandler(e){
          event = e || window.event;
          var keycode = event.which || event.keyCode;
          keyLookUp[keycode](e);
       }

       function leftKey(e){

        }

       function rightKey(e){

       }

       function DownKey(e){

       }

})();

How can i modify the above code to handle the multiple key press functionality also?? like pressing Shift + left key

bhavya_w
  • 9,186
  • 9
  • 29
  • 38

1 Answers1

0

How can i modify the above code to handle the multiple key press [such as] pressing Shift +

The keys Shift, Ctrl, Alt and Alt Gr are modifier keys, this means that they're sent as part of the event you call e and are stored as e.shiftKey, e.ctrlKey, e.altKey and e.altGraphKey, respectively.

So what does this mean for you? If you want to keep your current structure, I see you as having three choices; you can

  1. write completely different functions for the modified versions, e.g.

    keyLookUp['37sc'] = leftKeyShiftCtrl;
    
    keyLookUp[
        keycode
        + (e.shiftKey ? 's' : '')
        + (e.ctrlKey? 'c' : '')
        + (e.altKey ? 'a' : '')
    ](e);
    
  2. look at these values in you current handlers

    // inside fn
    if (e.shiftKey) {/* different code path */}
    
  3. pass these as parameters into your handlers (which take extra args)

    function leftKey(e, shift, ctrl, alt) { /* ... */ }
    
    keyLookUp[keycode](e, e.shiftKey, e.ctrlKey, e.altKey);
    

For any combination of keys, you need to track keydown and keyup, see this question

Community
  • 1
  • 1
Paul S.
  • 64,864
  • 9
  • 122
  • 138
  • Yaa i already looked at that question....its getting more complicated than i thought...thanx for your insight though.. – bhavya_w Sep 27 '14 at 14:24