Press a KEY to play a drum sound


I am currently building a Drum Machine project now, and I am stuck, with just one test left to go.
You can check out my project here:

My problem is, if you press a key from your keyboard, the program should play the related note, but it can’t seem to do that. Below is the code I am working on right now.

$ (document) .keydown (function (event) {
  alert (event.keyCode);

I am trying to use the above code as a basis, to make the sound play, but it seems that the function does not do anything at all.
Another problem is that when you add the code, you can not play drum sounds by mouse clicks which used to work fine.
It’s like you tried to fix one, but you end up in a situation where none of the functions work.

It is really frustrating that I cannot decide whether this is a problem with the Codepen, or I am addressing the issue from a completely wrong angle.

Answers can be either jQuery or pure Javascript; I would appreciate your help.

1 Like
window.addEventListener('keydown', function (event) {
  alert (event.keyCode);
1 Like

Thanks for this, @jenovs! I got super close to getting this to work, but I was writing document.addEventListener as opposed to window.addEventListener! Phew! One step closer :slight_smile:

Hi, @jenovs

This is a little too late thank you note for you, but I wanted to say thank you anyway.

The following is what I coded after you gave me a starter to follow. Check out the code below.

window.addEventListener('keydown', function (event) {
    var k=event.keyCode;
    if(k===81) playSound('Q'); else
    if(k===87) playSound('W'); else
    if(k===69) playSound('E'); else
    if(k===65) playSound('A'); else
    if(k===83) playSound('S'); else
    if(k===68) playSound('D'); else
    if(k===90) playSound('Z'); else
    if(k===88) playSound('X'); else
    if(k===67) playSound('C');

Thank you.

PS: It’s pretty much challenging to add back ticks from my iPhone keyboard.

I would have never known whether I could do it with such an easy piece of code if I had not asked here in this forum.

This forum really helps me a lot, and I definitely seem to like this forum petty much.

I’m guessing you fixed it because it worked well for me.
Its great and I love the keys you chose. It makes it so much easy to play which makes it fun.
Great work. Keep it up.