keyCode - Javascript

-1

Good evening my dear, I'm doing a 'function' in javascript but it's not running on my Chrome browser.

  function move(){
         var obj = document.getElementById("dv1");
         var tecla = KeyboardEvent.keyCode;
         /*37 -Esquerda - 38-cima - 39-direita 40-baixo*/

         if(tecla==37){
            px-=10; //salto
            obj.style.left= px +"px";
         }else if(tecla==38){
            py-=10;
            obj.style.top= py+"px";
         }else if(tecla==39){
            px+=10;
            obj.style.left=px+"px";
         }else if(tecla==40){
            py+=10;
            obj.style.top=py+"px";
         }else if(tecla==13){
           alert("este evento foi para o beleleu");
           obj.removeEventListener("keydown",move); 
          }
}

document.addEventListener("keydown",move);

The idea is trivial to "move a square" with "keydown", however when inspecting the Chrome console there is an error in the "event.keyCode" that I can not determine. Thank you in advance for your cooperation.

    
asked by anonymous 04.01.2019 / 00:58

1 answer

0

When you create a function that is used in a callback , you should be aware of arguments / parameters that are passed. Every function that is executed in an event, receives as argument / parameter a Event object, according to the triggered event.

When trying to get the key that was "triggered", you are trying to do it on the "native" object, KeyboardEvent ; instead of using the object Event , which is always passed as argument / parameter, as I mentioned earlier.

So, instead of using KeyboardEvent , set a parameter (i.e. event ) in the move function, and get the key pressed. And instead of keyCode (which in fact is deprecated), you can use which , thus:

function move(event) {
    var obj = document.getElementById("dv1");
    var tecla = event.which;
    /*37 -Esquerda - 38-cima - 39-direita 40-baixo*/

    if(tecla==37){
        px-=10; //salto
        obj.style.left= px +"px";
    } else if (tecla==38) {
        py-=10;
        obj.style.top= py+"px";
    } else if (tecla==39) {
        px+=10;
        obj.style.left=px+"px";
    } else if (tecla==40) {
        py+=10;
        obj.style.top=py+"px";
    } else if (tecla==13) {
        alert("este evento foi para o beleleu");
        obj.removeEventListener("keydown", move); 
    }
}
document.addEventListener("keydown", move);

I hope I have helped!

    
04.01.2019 / 01:15