2 years ago
#377123

Tommaso Orlandi
addEventListener function
I' currently studying js and DOM and there is something about the eventListener I really don't understand.Here's my problem. I create a function that takes one argument, check if that arguments is equal to W , A or S and play a sound.There's nothing wrong with this function,it works perfectly.
function playSound(key) {
  switch (key) {
    case "w":
      var crash = new Audio("sounds/crash.mp3");
      crash.play()
      break;
    case "a":
      var kickBass = new Audio("sounds/kick-bass.mp3");
      kickBass.play()
      break;
    case "s":
      var snare = new Audio("sounds/snare.mp3");
      snare.play()
      break;
    default:
Now I'd like to start this function whenever the "keydown" event is called. The question is: why is the following code working
document.addEventListener ("keydown" , function(event) {
   playSound(event.key);
};
while this one is not?
document.addEventListener ("keydown" , playSound(event.key));
Why do I need an anonymous function to call another function when I could call the function I need straight away?I'm very confused
javascript
function
addeventlistener
keydown
0 Answers
Your Answer