I am having troubles understanding why the code below works, and I think my confusing arises with the callback to "event" in this case. I have a few images that when clicked or a corresponding keypress is logged, a sound will play. While everything works, I can't understand why the below code uses "event" instead of just using an empty function and call to "this" (ie: this.key)
I have tried to use the "this" method but it didn't work. A bit of research and I found I had to use "event" in my function.
function addListenerToAllDrums() {
//store buttons in array
var buttonArray = document.querySelectorAll(".drum");
//iterate thru each btn
for (var i = 0; i < buttonArray.length; i++) {
//add a listener each iter.
buttonArray[i].addEventListener("click", function () {
//store html of button (ie: `w`) to variable
var buttonInnerHTML = this.innerHTML;
//the stored html is passed to the checkSound function
checkSound(buttonInnerHTML); //ie: `w` = case w
});
}
}
//check for keypress
document.addEventListener(`keydown`, function (event) {
//store the key in a variable
var pressedKey = event.key
//passes pressedKey as string (ie: `w`) to checkSound(`w`)
checkSound(pressedKey);
});
//make a sound dependant on button press or keypress functions
function checkSound(input) {
//Create Switch Statement based on keypress/button click input
switch (input) {
case `w`:
var snare = new Audio('sounds/snare.mp3');
snare.play();
case `a`:
var tom1 = new Audio('sounds/tom-1.mp3');
tom1.play();
break;
case `s`:
var tom3 = new Audio('sounds/tom-3.mp3');
tom3.play();
break;
case `d`:
var kick = new Audio('sounds/kick-bass.mp3');
kick.play();
break;
case `j`:
var tom4 = new Audio('sounds/tom-4.mp3');
tom4.play();
break;
case 'k':
var tom2 = new Audio('sounds/tom-2.mp3');
tom2.play();
break;
case `l`:
var crash = new Audio('sounds/crash.mp3');
crash.play();
break;
default:
console.log(this.innerHTML)
}
}
addListenerToAllDrums();
How can my clicks work with "this" but keypresses need "event"?