I am working on a basic JavaScript program that plays sounds when I click buttons. I am using a switch to be able to tell which sound should be played. I am also using event listeners on each button to respond to clicks.
When I do something like:
currentButton.addEventListener("click", function() {
// code here
})
It works fine. However, I want to try defining the function outside of the event listener, and then passing it to the event listener.
I have a simplified example here:
function setPathAndPlay(currentButton) {
let audioPath;
switch (currentButton.innerHTML) {
case "w": {
audioPath = "./sounds/crash.mp3";
break;
}
}
const audio = new Audio(audioPath);
audio.play();
}
for (let currentButton of drumArray) {
currentButton.addEventListener("click", setPathAndPlay(currentButton))
}
This does not work. I believe what is happening is setPathAndPlay(currentButton)
is directly running as it is a function call, which is causing problems. How can I pass the currentButton
to setPathAndPlay
though? Since that function needs access to the button.
I'm not sure what to try to fix this. I believe something with an arrow function or some sort of wrapper function may work. I am looking to find a solution as simple as possible to help me understand. Thank you!