-1

I assign an event listener inside the first function whenever I press the 1 in my keyboard which is 49 in keyCode it will trigger the first function which will console the A and S whenever you try to press it. then if I press the 2 in my keyboard which is 50 in keyCode it will then trigger the second function which will console the D and F whenever you press it. My problem is after I called the first function then call the second function, how can I disable the first function that will prevent the press of A and S ? In short, how to disable the event listener of function I called whenever I will call the new function ?

<body>

</body>
<script>
    document.body.addEventListener('keydown',function(e){
        if(e.keyCode == 49){
            document.body.addEventListener('keydown',function(e){
                switch(e.keyCode){
                    case 65:
                    console.log('you pressed A')
                    break;
                    case 83:
                    console.log('you pressed s')
                    break
                }
            })
        }else if(e.keyCode == 50){
            document.body.addEventListener('keydown',function(e){
                switch(e.keyCode){
                    case 68:
                    console.log('you pressed d')
                    break;
                    case 70:
                    console.log('you pressed f')
                    break
                }
            })
        }
    });
</script>
Justin Herrera
  • 526
  • 4
  • 11

1 Answers1

0

To remove an event listener, the function must have a name to reference, so that you can reference which event listener to remove. For example:

function myFunction() {
  // code here
}
document.body.addEventListener("keydown", myFunction);

and to remove it:

document.body.removeEventListener("keydown", myFunction);

Without assigning functions to names, JavaScript doesn't know which event listener to remove, because you can have multiple functions binded to one element.

So to change up your code, it should be:

document.body.addEventListener("keydown",function(e) {
  if (e.keyCode == 49) {
    document.body.addEventListener("keydown", verticalMoves);
  } else if (e.keyCode == 50) {
    document.body.addEventListener("keydown", horizontalMoves);
  }
}

function verticalMoves(e) {
  switch(e.keyCode) {
    case 65: console.log("you pressed A"); break;
    case 83: console.log("you pressed S"); break;
  }
  document.body.removeEventListener("keydown", verticalMoves);
}
function horizontalMoves(e) {
  switch(e.keyCode) {
    case 68: console.log("you pressed D"); break;
    case 70: console.log("you pressed F"); break;
  }
  document.body.removeEventListener("keydown", horizontalMoves);
}
Coco Liliace
  • 311
  • 5
  • 14