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
Solution 1:
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.
Solution 2:
Try this:
$('input:text').keypress(function(e) {
if (e.keyCode == 0 || e.keyCode == 32) // `0` works in mozilla and `32` in other browsersconsole.log('space pressed');
});
Solution 3:
Try to bind your key event listener to the jQuery $(document) object;
<!DOCTYPE htmlPUBLIC"-//W3C//DTD HTML 4.01//EN"><html><head><scripttype="text/javascript"src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script><scripttype="text/javascript">
$(document).ready(function() {
$(document).keydown(function(e) {
if (e.keyCode == '32') {
alert('space');
}
});
});
</script></head><body></body></html>
Solution 4:
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
Post a Comment for "Javascript Event Triggered By Pressing Space"