Lesson 165 – Complete 2020 Web Development Bootcamp

Lesson 165 – Using Keyboard Event Listeners to Check for Key Presses

In this lesson, we learned how to take the switch code from the previous lesson and add a keyboard event listener so that when the letter on the keyboard which corresponds to the letter on the image is pressed the drum will sound.

This is the code incorporating both an event listener for a click on the image and an event listener for a key press.

var numberOfDrumButtons = document.getElementsByClassName("drum").length;

for (var i = 0; i < numberOfDrumButtons; i++) {
	document.getElementsByClassName("drum") 
        [i].addEventListener("click", function(){

          var buttonInnerHTML = this.innerHTML;
          playSound(buttonInnerHTML);

            });

  }


document.addEventListener("keydown",function(event) {
  playSound(event.key);
  });

function playSound(key) {

	switch (key) {
	  case "w":
	  var kickBass = new Audio("sounds/kick-bass.mp3");
	  kickBass.play();
	break;

	case "a":
	  var snare = new Audio("sounds/snare.mp3");
	  snare.play();
	break;
	case "s":
	  var tom1 = new Audio("sounds/tom-1.mp3");
	  tom1.play();
	break;
	case "d":
	  var tom2 = new Audio("sounds/tom-2.mp3");
	  tom2.play();
	break;
	case "j":
	  var tom3 = new Audio("sounds/tom-3.mp3");
	  tom3.play();
	break;
        case "k":
	  var tom4 = new Audio("sounds/tom-4.mp3");
	  tom4.play();
	break;
	case "l":
	  var crash = new Audio("sounds/crash.mp3");
	  crash.play();
	break;

	default: console.log(buttonInnerHTML);

		}

	}