Search code examples
javascriptarraysaudioonkeyup

How do I use JavaScript to add a function that calls another function onkeyup?


So basically I have a little website that acts like a drum-kit. I want it to play sound when you click an on screen element and then I also want the same on screen elements to be able to be "clicked"" whenever I press the corresponding number-pad key.

I got it to play when i click on it, I just cannot get the onkeyup function to work.

  const sounds = document.querySelectorAll('.sound');
  const drumPads = document.querySelectorAll('.drumpadContainer');
  const keycodes =[
    49,
    50,
    51,
    52,
    53,
    54
  ]

  //Can i make sound??

  drumPads.forEach((drumpad, index) => {
    drumpad.addEventListener('click', function() {
      console.log("You clicked a button");
      sounds[index].currentTime = 0;
      sounds[index].play();
    })
    drumpad.addEventListener('onkeyup', function() {
      if (onkeyup == keycodes[index]){
        drumPads[index].click();
      }
    })

  });



})

Solution

  • The keyup handler should be on window. It should get the index of the key code, then use that to get the index of the corresponding element to click.

    window.addEventListener("keyup", function(e) {
        var index = keycodes.indexOf(e.keyCode);
        if (index > -1) {
            drumPads[index].click();
            e.preventDefault();
            e.stopPropagation();
        }
    }