Execute JS code after pressing the spacebar
In JQuery events are normalised under which event property.
You can find any key value here eg:spacebar value(32).
This function may help you.
$(window).keypress(function(e) {
if (e.which === 32) {
//Your code goes here
}
});
There was a method with keyCode
, which is now deprecated as mentioned in the comments. Thus, I've edited the answer.
Currently there're couple of another ways of doing it. I am also including a deprecated one just in case.
document.body.onkeyup = function(e) {
if (e.key == " " ||
e.code == "Space" ||
e.keyCode == 32
) {
//your code
}
}
BONUS: I've made a quick snippet to get key code of any character. It's pretty easy to use: just type any letter in the textbox below.
Pro tip: you could also run a snippet using different browsers to have fallbacks just in case.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><input type="text" placeholder="enter a char here" id="char-finder"><p class="key"> <pr>key</pr> for <pr class="char">space</pr> is <pr class="tr"> </pr></p><p class="code"> <pr>code</pr> for <pr class="char">space</pr> is <pr class="tr">Space</pr></p><p class="keycode"> <pr>keyCode</pr> for <pr class="char">space</pr> is <pr class="tr">32</pr></p><script>document.getElementById('char-finder').onkeyup=function(e){key=e.key==" " ? " " : e.key; code=e.code; kcode=e.keyCode; char=e.key==" " ? "space" : e.key; $(".key .tr").html(key); $(".code .tr").html(code); $(".keycode .tr").html(kcode); $(".char").html(char);}</script><style>body{font-size: 17px;}input{border: 1px solid grey; border-radius: 10px; font-size: 15px; padding: 5px;}pr{font-family: Menlo; padding: 3px; border-radius: 5px; font-size: 15px; display: inline-flex; justify-content: center; background: rgb(230, 230, 230); min-width: 20px;}.key pr:first-child{background: rgb(0, 230, 230);}.keycode pr:first-child{background: rgb(230, 0, 50); color: white;}.code pr:first-child{background: rgb(230, 230, 0);}pr.tr{margin-left: 5px; border: 1px solid black; background:transparent;}</style>
The 2019 version of this would be: (works in all major browsers - Chrome, Firefox, Safari)
Spec link - https://www.w3.org/TR/uievents/#dom-keyboardevent-code
code holds a string that identifies the physical key being pressed. The value is not affected by the current keyboard layout or modifier state, so a particular key will always return the same value. The un-initialized value of this attribute MUST be "" (the empty string).
// event = keyup or keydown
document.addEventListener('keyup', event => {
if (event.code === 'Space') {
console.log('Space pressed')
}
})