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

1

So far I have only this code snippet:

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

I wanted to change this keyup by pressing space. And I'm also using a text area in HTML to receive keyboard input, how do I get it from anywhere on the screen?

    
asked by anonymous 09.06.2017 / 20:22

2 answers

1

You can add this event handset to document or window to listen to events on the whole 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!');
});
    
09.06.2017 / 20:27
1

Just check if the 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>Digiteemmim<inputtype="text" id="teste"></input>
    
09.06.2017 / 20:27