How to create an event where when the user presses the space key something happens?

Asked

Viewed 752 times

1

For now I have only this bit of code:

personagemPular.on("keyup",function(){

I wanted to trade this keyup for pressing space. And I’m also using a area text in HTML to receive keyboard entries, as I do to receive from anywhere on the screen?

2 answers

1


You can add this event headset to document or window to listen to events on the entire page and search for the property that says the key code.

Example:

window.addEventListener('keyup', function(e) {
  var codigoTecla = e.which || e.keyCode || 0;
  var space = codigoTecla == 32;
  if (space) alert('O space foi pressionado!');
});

1

Just check if Event.keycode was 32, which is the space.

Click on the example below and press space

$('#teste').keyup(function (e) { 
   var press = e.which || e.keyCode || 0;
   if(press == 32)
   {
      alert('espaço foi pressionado');
   }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Digite em mim<input type="text" id="teste"></input>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.