Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript event triggered by pressing space

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.

like image 430
Henrik Skogmo Avatar asked Jun 01 '11 09:06

Henrik Skogmo


People also ask

What is keypress event in JavaScript?

The keypress event is fired when a key that produces a character value is pressed down. Examples of keys that produce a character value are alphabetic, numeric, and punctuation keys. Examples of keys that don't produce a character value are modifier keys such as Alt , Shift , Ctrl , or Meta .


1 Answers

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.

like image 179
Félix Saparelli Avatar answered Sep 20 '22 10:09

Félix Saparelli