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.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Henrik O. Skogmo
  • 2,013
  • 4
  • 19
  • 26

4 Answers4

53

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.

Félix Saparelli
  • 8,424
  • 6
  • 52
  • 67
  • 1
    On Firefox, this intercepted Ctrl+J, so I changed the first condition to `e.charCode === 32`. – Noumenon Feb 10 '16 at 17:24
  • From the answer right below: "`0` works in mozilla and `32` in other browsers". This is probably not relevant anymore, but you should be using the modern [.key](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key) instead anyway. – Félix Saparelli Mar 05 '18 at 23:45
  • Works with `e.key === ' '` in Chrome, Firefox and Safari – Chaki_Black Aug 12 '21 at 06:33
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');
});
Patrick Hund
  • 19,163
  • 11
  • 66
  • 95
thecodeparadox
  • 86,271
  • 21
  • 138
  • 164
5

This code can be used:

$(window).keypress(function(e) {
  if (e.keyCode == 0 || e.keyCode == 32) {
    console.log('Space pressed');
  }
});


Explaination:
The $(window).keypress(function(e) waits for the user to press any key and stores the data of the key pressed in the argument 'e'.
Then if (e.keyCode == 0 || e.keyCode == 32) checks if the code of the key pressed is equal to the code of spacebar, that is 0 or 32. If this returns false then any other key is pressed and the code ends.

Some commonly used keycodes:

  • backspace:8
  • tab:9
  • enter:13
  • shift:16
  • ctrl:17
  • alt:18
  • caps lock:20
  • escape:27
  • (space):32
  • 0-9:48-57
  • a-z:65-90
  • numpad0-numpad9:96-105
divykj
  • 576
  • 6
  • 12
5

Try to bind your key event listener to the jQuery $(document) object;

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
  <head>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
    <script type="text/javascript">
      $(document).ready(function() {
        $(document).keydown(function(e) {
          if (e.keyCode == '32') {
            alert('space');
          }
        });
      });
    </script>
  </head>
  <body>
  </body>
</html>
Karl-Bjørnar Øie
  • 5,554
  • 1
  • 24
  • 30