undefined parameter in JavaScript

54 views Asked by At

The following JS code enables a demo drum kit:

var numberOfdrumButtons = document.querySelectorAll(".drum").length;
// call 2 functions when the click-event is triggered
for (var i = 0; i < numberOfdrumButtons; i++) {
    document.querySelectorAll(".drum")[i].addEventListener("click", function (){

    var buttonInnerHTML = this.innerHTML;

    makeSound(buttonInnerHTML);
    buttonAnimation(buttonInnerHTML);    

    });
}
// call 2 functions when the keydown-event is triggered
document.addEventListener("keydown", function(event){

    makeSound(event.key);
    buttonAnimation(event.key);    

  
});
//function to make sound
function makeSound(key){

    switch (key) {
        case "w":
            var audio = new Audio("sounds/crash.mp3");
            audio.play();
        case "a":
            var audio = new Audio("sounds/kick-bass.mp3");
            audio.play();
        case "s":
            var audio = new Audio("sounds/snare.mp3");
            audio.play();
        case "d":
            var audio = new Audio("sounds/tom-1.mp3");
            audio.play();
        case "j":
            var audio = new Audio("sounds/tom-2.mp3");
            audio.play();
        case "k":
            var audio = new Audio("sounds/tom-3.mp3");
            audio.play();
        case "l":
            var audio = new Audio("sounds/tom-4.mp3");
            audio.play();
        
            
            break;
       
        default:
            break;

       }

    }
//function to add an animation
function buttonAnimation(currentKey){

    var activeButton = document.querySelector("." + currentKey);
    activeButton.classList.add("pressed");
    setTimeout(function() {
        activeButton.classList.remove("pressed");
    }, 100
    
    )

}

So my question is about the currentKey parameter in the function buttonAnimation. Where does it come from? How can it function if it's not defined before? How does it work? I stumbled across the same kind of value in another JS exercise and I have no clue. There the parameter is called currentColor.

I tried to use as the parameter event instead, but the function buttonAnimation(currentKey) doesn't work. To be specific the setTimeout function didn't work then.

1

There are 1 answers

1
nq099hu On

The organization of your code is the key to it all. You begin with calling functions that are not yet defined. Kindly note that the currentKey is just a parameter that is replaced with buttonInnerHTML parameter or event.key parameter. Organizing your code might come in handy when trying to understand the logic or debugging.