Skip to content

JavaScript trigger spacebar | Execute JS code after pressing

  • by

The spacebar keycode is 32. Let’s try to trigger the space key with keycode in JavaScript. Checks if the code of the key pressed is equal to the code of the spacebar,

JavaScript trigger spacebar Example

HTML example executes JS code after pressing the spacebar.

<!DOCTYPE html>
<html>
<body>
  <input type="text" id="myInput">

  <script>

    window.onkeypress = function(event) {
      if (event.which == 32) {
        alert(event.code + " " + event.which); 
      }
    }
  </script>

</body>
</html>

Output: This will be executed after you hit the spacebar.

Auto Trigger space bar key

Emulate the client by pressing the space bar using JavaScript.

When the browser parses your HTML and reaches a <script> tag, it immediately executes the JavaScript in it. It can however happen, that the rest of the document is not loaded yet.

Example trigger a space key event with keycode.

<!DOCTYPE html>
<html>
<body>
  <script>
    document.addEventListener('keydown', function(ev){
      alert(ev.which + " " + ev.code);
    });

    (function() {
      var e = new Event('keydown');
      e.which = e.keyCode = 32;
      e.code = "Backspace"
      document.dispatchEvent(e);   
    })();
  </script>

</body>
</html>

Output:

With text box backspace button

<!DOCTYPE html>
<html>
<body>
  <textarea id="textbox"></textarea>
  <button class="button" onclick="backspace()" > BACKSPACE BUTTON </button>

  <script>
    var textbox = document.getElementById('textbox');

    function backspace()
    {
      var ss = textbox.selectionStart;
      var se = textbox.selectionEnd;
      var ln  = textbox.value.length;

      var textbefore = textbox.value.substring( 0, ss );    
      var textselected = textbox.value.substring( ss, se ); 
      var textafter = textbox.value.substring( se, ln );    

      if(ss==se) 
      {
        textbox.value = textbox.value.substring(0, ss-1 ) + textbox.value.substring(se, ln );
        textbox.focus();
        textbox.selectionStart = ss-1;
        textbox.selectionEnd = ss-1;
      }
      else 
      {
        textbox.value = textbefore + textafter ;
        textbox.focus();
        textbox.selectionStart = ss;
        textbox.selectionEnd = ss;
      }

    }
  </script>

</body>
</html>

Output:

text box backspace button JavaScript

Do comment if you have any doubts and suggestions on this JS trigger code.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading