Executing a keydown function while video streams

Hello awesome coding experts,

I’m combining my attempts to learn Javascript with my main job as a music educator. To that end, I’m working on a drumming web app so students can experiment with different djembe sounds, and I have embedded some YouTube videos of West African drumming patterns. I would like users to be able to play the drums in time with the drummer in the video, but the keydown function does not execute while the embedded video is streaming. Any tips?

The code is here (adapted from Wes Bos’s Javascript 30 series): https://codepen.io/srhbishop/pen/mdebrGJ. (There’s no sound right now because the .wav files are hosted locally on my hard drive,)

Hi. After you press play, the video is being focused, and if you press any key, it’ll seem like it’s not being pressed, but that’s only because the video is the one “receiving” those key presses. If you click outside the video, then keydown function will execute normally. At least that is what happens in the code you linked to.

I think you may have to use the YouTube Player API and some “hackyness” to solve this. Using the API you can get to the onStateChange on the player and give focus to a hidden element on the page. It will however not really work for multiple videos so you can also implement a video load function to load each of the videos on some button click.

Here is a quick example.

Thanks to both; this is helpful. I’m thinking I’ll try using onStateChange with a video playlist rather than separate videos…will ask students/teachers which is most user-friendly.

1 Like