How to assign different audio to different buttons after clicked event

  <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>
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');;  

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.


  • 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's class for that.

    The element's class can be accessed using the for the string with all of the classes or 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.

    const tekan = document.querySelectorAll(".drum");
    tekan.forEach(drum => {
      drum.addEventListener("click", play);
    const drumSoundFiles = {
      "w": "crash.mp3", 
      "a": "kick.mp3", 
      "s": "snare.mp3",
      "d": "tom1.mp3", 
      "j": "tom2.mp3",
      "k": "tom3.mp3",
      "l": "tom4.mp3"
    function play(event) {
      const pressedKey =[0]
      const soundFile = drumSoundFiles[pressedKey]
      const audio = new Audio(`sounds/${soundFile}`)

    Remember to map each key in the drumSoundFiles object to the correct sound.