tags:

views:

150

answers:

1

I'm making a typing tutor program using javascript. Everything is going well except that if activates browser hotkeys which disrupts the functionality of the program. When I press the single quote in Firefox it triggers "Quick find (links only)" short cut and in all browsers when I press space the page scrolls down a page. Everything is working fine outside of this. Here's the code in the head:

<script type="text/javascript">
$(document).ready(function() {
    executeType();
});
</script>

And the code I am using to capture the keyboard (simplified, but tested):

function executeType() {
    $(document).keydown(function(event) {
           alert(event.keyCode);
    });
}
A: 

If you want to stop keypresses from having their normal default behaviour, you should return false from the event handler.

Any keypresses that you pick up and do something with, you should cancel the default action for. However, be careful not to over-block by picking up things like ctrl-key combinations which the user is likely to want to continue to use for browser shortcuts.

$(document).keypress(function(event) {
    if (event.ctrlKey || event.altKey || event.metaKey)
        return;
    // do something with keypress
    return false;
});

(This still blocks single-key actions such as page-up/down and F5-to-refresh though, which isn't great. You'd generally look at the key code to detect only the keys you wanted to handle yourself, letting the rest through. Aside: I used keypress here rather than keydown since Opera doesn't support preventing the default action on keydown.)

bobince