Javascript event triggered by pressing space

Henrik Skogmo picture Henrik Skogmo · Jun 1, 2011 · Viewed 58.8k times · Source

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.

Thank you in advance!

Answer

Félix Saparelli picture Félix Saparelli · Jun 1, 2011

These events bubble up, so if you're trying to trigger the event wherever your focus is (ie. not in an input), just bind a handler on window:

$(window).keypress(function (e) {
  if (e.key === ' ' || e.key === 'Spacebar') {
    // ' ' is standard, 'Spacebar' was used by IE9 and Firefox < 37
    e.preventDefault()
    console.log('Space pressed')
  }
})

Also see the list of all .key values.