Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
165
rated 0 times [  170] [ 5]  / answers: 1 / hits: 69950  / 13 Years ago, wed, june 1, 2011, 12:00:00

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.


More From » jquery

 Answers
10

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.


[#91934] Tuesday, May 31, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
chelseyn

Total Points: 36
Total Questions: 85
Total Answers: 89

Location: Laos
Member since Fri, Sep 11, 2020
4 Years ago
;