Javascript Key Shortcut Manager





0
Date Submitted Tue. Dec. 4th, 2007 10:32 AM
Revision 1 of 1
Helper HRCerqueira
Tags JavaScript | Key | Web
Comments 2 comments
A simple, yet powerful (what a cliché) way of resgistering javascript keyboard shortcuts. Register any kind of keyboard shortcuts, and if applicable, override the browser default action.

Example usage and more info here:

Javascript Keyboard Shortcut Manager

var ShortcutMan = {};

ShortcutMan.getEventCode = function(evt) {
        //IE browsers don't pass the event object as an argument, so get them from the window object
        if (!evt)
                var evt = window.event;
               
        if (evt.keyCode) //on IE use keycode
                var code = evt.keyCode;
        else if (evt.which) //on mozilla use wich
                var code = evt.which;
               
        if (code >= 65 && code <= 90) //let's just use lower case codes
                code = code + 32;
               
        var ctrl = evt.ctrlKey ? 'c' : ''; //is ctrl pressed
        var alt = evt.altKey ? 'a' : ''; //is alt pressed
        var shift = evt.shiftKey ? 's' : ''//is shift pressed
       
        return ctrl + alt + shift + code;        //put all the pieces together and return the string
}

//a hash to store the actions in code / action pairs
ShortcutMan.keyShortcuts = {};

ShortcutMan.registerShortcut = function(code, action) {
        //if the code is not in the correct form, do nothing
        if (!/^c?a?s?\d{1,3}$/.test(code))
                return;
       
        //store the action in the keyshortcut hash
        ShortcutMan.keyShortcuts[code] = action;
}

ShortcutMan.readShortcut = function(evt) {
    //convert the event object in a keyboard shortcut code
        var code = ShortcutMan.getEventCode(evt);
       
        //if there is an action associated with that keystroke
        if (typeof(ShortcutMan.keyShortcuts[code]) == 'function') {
                //execute it
                ShortcutMan.keyShortcuts[code]();
                //and override the browser default behaviour
                document.defaultAction = false;
        } else //otherwise just tell the browser to keep on what hes doing
                document.defaultAction = true;
               
        return document.defaultAction;
}


//attach the readShortcut method to the onkeypress event in the document
document.onkeypress = ShortcutMan.readShortcut;
 

Hernâni Cerqueira

www.hrcerqueira.com

Comments

Comments Adjustments
Fri. Dec. 14th, 2007 4:23 PM    Scripter Fordiman
Comments I've gotta vote down...
Wed. Apr. 2nd, 2008 3:02 PM    Scripter sehrgut

Voting

Votes Up


Syntax Master dannyboy
Scripter Fordiman

Votes Down


Scripter i_kenneth
Scripter sehrgut