Execute JS code after pressing the spacebar

There’re couple of ways to do this. I am also including a deprecated one with keyCode (from the original answer) just in case (it still seems to work actually as of 2023).

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 and keyCode for any character.

Usage: 1) type in any letter 2) profit!

Pro tip: you could also run a snippet in 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">&nbsp;</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==" " ? "&nbsp;" : 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>

Leave a Comment