Article | Talk | Edit | History  

Capturing key events in Javascript

From the World Wide Wiki

"We want bread, yes. But also roses." - The Bread and Roses protest

Jump to: navigation, search

To capture key events in Javascript (in other words, prevent higher elements, like the document itself, from receiving the events), just prepend your handler with a return statement, and then return false from the callback. For instance, if I want a textarea to absorb CTRL-S events so the browser doesn't try to save the webpage to file, I could do this:

<script type='text/javascript'>
  function myKeyDownCallBack(event){
    //This is the keycode for the letter s. This code doesn't work in all
    // browsers, but there's a way to do it everywhere.
    if(event.keyCode == 83 && event.ctrlKey){
      //Process the ctrl-s event if desired
      //Prevent others from getting the event
      return false;
    }
    //If we didn't capture the event, let it continue to bubble up.
    return true;
  }
</script>

<textarea onkeydown="return myKeyDownCallBack(event);"/>