views:

566

answers:

3

In gmail, for example, when one presses CTRL+B, instead of it getting passed to the browser (which would normally bring up some sort of bookmark manager), it hijacks it for formatting purposes, i.e. turn on bold formatting for the message ur in the middle of comoposing. Same for C-i, C-u. How is this done?

A: 

Use the onkeydown or onkeyup event to fire a handler function:

var body = document.getElementsByTagName("body")[0];
body.onkeydown = function(event) {
    var str = "";
    for (var prop in event) {
        str += prop + ": " + event[prop] + "<br>";
    }
    body.innerHTML = str;
};

With that you can see what properties an event object has.

Gumbo
+4  A: 

You would attach an onkeydown or onkeyup event handler to the global document object. For example, if I wanted to make the title bar change to "asdf" each time Ctrl-M was pressed, I would register the event handler through window.onload, like this:

window.onload = function()
{
    document.onkeydown = function(event)
    {
        var keyCode;

        if (window.event) // IE/Safari/Chrome/Firefox(?)
        {
            keyCode = event.keyCode;
        }
        else if (event.which) // Netscape/Firefox/Opera
        {
            keyCode = event.which;
        }

        var keyChar = String.fromCharCode(keyCode).toLowerCase();

        if (keyChar == "m" && event.ctrlKey)
        {
            document.title = "asdf";
            return false;  // To prevent normal minimizing command
        }
    };
};

W3Schools has more information on using these events: onkeydown and onkeyup.

Also, I think I should note that there are some discrepancies across browsers in regards to the event properties (like, for example, in Firefox, you're supposed to access the keycode through event.which, while in IE it's event.keyCode, although Firefox may support event.keycode—confusing, isn't it?). Due to that, I'd recommend doing this stuff through a JavaScript framework, such as Prototype or jQuery, as they take care of all the icky compatibility stuff for you.

htw
Could you give an example please?For (meta- (:P))example, show how to change the document's title to the text 'asdf' when the key combo CTRL+M is used. Thanks, much appreciated.
@asdf: Sure, I expanded my answer for you. Hope it helps.
htw
@htw: yep, thanks alot :)Now... You've got netscape/firefox/opera/ie covered, does that code account for safari/chrome as well?
@asdf: Yup. Oddly enough, I found that event.keyCode actually works in Firefox, for some reason, even though W3Schools says it shouldn't…weird. Either way, I still recommend that you should do this through either Prototype or jQuery: see dplante's answer for an example of how to do it in jQuery.
htw
+2  A: 

Here is the source for an HTML page that uses jQuery and does what htw's solution does

Hope this helps somebody! I needed a rep of 50 to post comments and I'm close (hint hint :))

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"&gt;
<html>
  <head>
    <title>Hijack Example</title>
    <script type="text/javascript" src="../scripts/jquery-1.2.1.js">
    </script>
    <script type="text/javascript">
        $(function(){
            document.title = "before keypress detected";
            $(document).keydown(function(event) {
                // alert('stuff happened: ' + msg + " " + event.keyCode);
                var keyChar = String.fromCharCode(event.keyCode).toLowerCase();
                if (keyChar == "m" && event.ctrlKey) {
                    document.title = "ctrl-m pressed!";
                }
            });
         });
    </script>
  </head>

  <body id="body">
    <p>Change the path to jquery above as needed (search for ../scripts/jquery-1.2.1.js)</p>
    <p>Watch the title bar, then press control-M, then watch the title bar again!</p>
  </body>
</html>
dplante