<h1 id="title">Drum 🥁 Kit</h1>
<div class="set">
<button class="w drum">w</button>
<button class="a drum">a</button>
<button class="s drum">s</button>
<button class="d drum">d</button>
<button class="j drum">j</button>
<button class="k drum">k</button>
<button class="l drum">l</button>
</div>
var tekan = document.querySelectorAll(".drum");
tekan.forEach(drum => {
drum.addEventListener("click", play);
})
function play() {
// const sound = ["crash.mp3", "kick.mp3", "snare.mp3", "tom1.mp3", "tom2.mp3", "tom3.mp3", "tom4.mp3"];
var audio = new Audio('sounds/crash.mp3');
audio.play();
};
When I click each button, it will only play the crash.mp3 audio, how do I assign different audio like the one in const sound to each button?
I tried to use this
keyword so that it changes the audio file source (/crash.mp3) in
var audio = new Audio('sounds/crash.mp3');
according to the button clicked. I guess my knowledge of this
keyword is still vague, or is there any way other than this? It would be great if I could only use Javascript
for this.
2
Answers
When an event listener is triggered, the callback function receives the
event
that triggered it as an argument, with it you can determine which button was clicked. In your case you can use the element’sclass
for that.The element’s class can be accessed using the
event.target.className
for the string with all of the classes orevent.target.classList
for a list containing a string for each class.For your use case
classList[0]
contains the relevant information as the key label is the first class.Remember to map each key in the
drumSoundFiles
object to the correct sound.Certainly! You may accomplish this by including the audio file location associated with each button as a data property in your HTML and then accessing this data attribute in your JavaScript code. Here’s how you can modify your HTML and JavaScript to accomplish this:
Each button in this amended HTML contains a data-sound property identifying the audio file to be played.
This refers to the button element that was clicked in the play function. You may access the value of the data-sound attribute associated with the clicked button by using this.getAttribute("data-sound"). The path to the matching audio file is then constructed using this value, and the Audio object is generated and played.
As a result, depending on the data-sound attribute value supplied in the HTML, each button will play a different audio file.