Drum Machine: Audio Does Not Play on Key Press Until a Button Is Clicked


I’m working on the drum machine frontend libraries project. When I press a key on my keyboard without first clicking any of the buttons on the screen, the audio does not play. For the audio to play on key press, I need to first click on any of the keys after the page has loaded.

Please what could be the issue?

You can find the app in its current state here (sorry, no CSS yet) and the code base here.

You can get it to work from the keyboard without clicking with your mouse if you first use the Tab key to put focus on one of the buttons. Clicking with the mouse on a button also puts focus on the button.

The reason you need focus to be on a button before you can trigger these with the keyboard is because your only event listeners are for clicks on the buttons. When your page first loads, no button has focus, and thus nothing is listening for those key presses on the keyboard.

The solution is to add an even listener to listen for those keyboard presses on an element that encompasses the entire page, such as the body. I would recommend you listen for keydown since you want the sound to play immediately when the key is pressed.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.