/** * Javascript library to handle a set of keybindings. * * The user should include this script, and then call setKeybinding(key, * callback) for each keybinding that is desired. This script will take care * of listening for keypresses and mapping them to the callback functions, or * doing nothing if no callback is set. * * $Horde: horde/templates/javascript/keybindings.js,v 1.5 2004/11/29 14:50:27 jan Exp $ * * See the enclosed file COPYING for license information (LGPL). If you did * not receive this file, see http://www.fsf.org/copyleft/lgpl.html. * * @version $Revision: 1.5 $ * @package Horde */ /** * A hash of keybindings. * * @var _keyMap */ var _keyMap = new Array(); /** * Set up the keypress listener. */ if (window.document.captureEvents != null) { window.document.captureEvents(Event.KEYPRESS); window.document.onkeypress = keyHandler; } else { window.document.onkeydown = keyHandler; } /** * Sets up a callback for a keycode. * * @param key The keycode to trigger on. * @param callback The function to call when "key" is pressed. Should be a * function. It gets the event and the keycode as parameters, * so that you can use one function to handle multiple keys if * you like. */ function setKeybinding(key, callback) { if (typeof _keyMap[key] == 'undefined') { _keyMap[key] = new Array(); } _keyMap[key][_keyMap[key].length] = callback; } /** * Invoked by the JavaScript event model when a key is pressed. Gets the * keycode (attempts to handle all browsers) and looks to see if we have a * keybinding defined for that key. If so, eval() it. * * @param e The event to handle. Should be a keypress. */ function keyHandler(e) { var e = e || window.event; /* Look in all the various places we might have to check for the * keycode. */ if (document.layers) { key = e.which; } else { key = e.keyCode; } /* If there's a keybinding defined for the key that was pressed, eval() * it, passing in the keycode and the event. */ if (_keyMap[key]) { for (var i = 0; i < _keyMap[key].length; i++) { if (eval(_keyMap[key][i] + '(e, ' + key + ');')) { e.returnValue = false; break; } } } }