-1

i'm building a drum machine and i want to be able trigger drum sounds with specific keys on the keyboard. I added event listeners for keypress and keydown events but the sounds are not played when those keys are pressed. The current JavaScript code to do this is below(I also used the function in an input element and it triggered the sound successfully);

document.getElementById('drumpad1').addEventListener('keypress', tFunction(event));
function tFunction(event) {
  var key = event.keyCode;     
  var char = String.fromCharCode(key);    
  var charUp = char.toUpperCase()
  if (char === 'q' || charUp === 'Q') {
      document.getElementById("beat").play();
  }
}

I also have tried document.body.addEventListener() didn't work. please help

Duke Sanmi
  • 67
  • 1
  • 6
  • `.addEventListener('keypress', tFunction(event));` should be `.addEventListener('keypress', tFunction);`. Give the method a callback, not an invocation – Taplar Jul 03 '20 at 16:35
  • 1
    Does this answer your question? [Why does click event handler fire immediately upon page load?](https://stackoverflow.com/questions/7102413/why-does-click-event-handler-fire-immediately-upon-page-load) – Taplar Jul 03 '20 at 16:35
  • Instead of `tFunction(event)` you should use `event => tFunction(event)`. – CherryDT Jul 03 '20 at 16:36
  • @CherryDT Why? Why make an extra anonymous method that is not needed? – Taplar Jul 03 '20 at 16:36
  • Because this will then also work with other cases like `event => fn(something, event, somethingElse)`. It will therefore probably be easier to understand and apply by the OP. But actually I didn't mean to correct your comment but the OP's code. Just `tFunction` of course works too in this case. – CherryDT Jul 03 '20 at 16:38
  • "Will work with other cases" isn't relevant. It's unnecessary for this case, and most cases, unless you have issues with scope changing. – Taplar Jul 03 '20 at 16:39

1 Answers1

1

Replace

document.getElementById('drumpad1').addEventListener('keypress', tFunction(event));

by

document.addEventListener('keypress', tFunction);

This will work if the document is in focus.

D. Pardal
  • 6,173
  • 1
  • 17
  • 37
  • https://stackoverflow.com/questions/7102413/why-does-click-event-handler-fire-immediately-upon-page-load This is a known duplicate – Taplar Jul 03 '20 at 16:35