Alex Rivera | Logout

Javascript event triggered by pressing space

Asked 2011-06-01T09:30:39.850
31

I am trying to get an event to trigger when I am on a page and press space, but I can't figure it out. Currently I am trying to use jQuery to accomplish a satisfying result.

I have tried using keydown, keyup and keypress, but it seems that you can only use it if you are actually inputting something to a form or field.

What I want is to trigger an alert when space is pressed.

Edit
Report

1 Answer

8

Try this:

$('input:text').keypress(function(e) {
    if (e.keyCode == 0 || e.keyCode == 32) // `0` works in mozilla and `32` in other browsers
       console.log('space pressed');
});
answered 2011-06-01T09:39:08.777

Your Answer