Javascript event triggered by pressing space
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');
});
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>
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.