Search code examples
javascriptjqueryeventhandler

Add different sounds to different buttons


I am working through a project using Javascript and jQuery. The projects requires me to add sounds to buttons. A different sound should play depending on the button I click. I know how to add a single audio file to buttons, but can someone help me with adding different audio to each button?

$(".btn").on("click" , function () {
    let buttonSound = $(this).attr("id");
    playSound(buttonSound);

});

My project gives a random color, which corresponds with a button. This code works to play the sound of that button, but it also plays that sound with my other buttons (instead of the sound they are suppose to play). The only way to change the sound is to refresh the screen, but this has the same issue, just with a different random button. Any help would be greatly appreciated.


Solution

  • .btn is indeed a too common selector to do something that specific.
    Instead you could try this better strategy, and that's by using the data-* attribute like:

    <button class="btn" data-sound="cat" type="button">Cat</button>
    <button class="btn" data-sound="dog" type="button">Dog</button>
    

    and then in jQuery:

    $("[data-sound]").on("click", function() {
      const buttonSound = $(this).data("sound");
      playSound(buttonSound);
    });
    

    or in pure JavaScript if you prefer:

    document.querySelectorAll("[data-sound]").forEach((elBtn) => {
      elBtn.addEventListener("click", () => {
        playSound(elBtn.dataset.sound);
      });
    });
    

    this way you get rid of ID selectors, and if needed you can have more than one button that plays the same sound - without running into issues related to duplicated IDs.
    Always use the data attribute when in need to store and retrieve arbitrary data in HTML.

    PS:
    Since you did not provided any code for the playSound function, for any future reader to this question, the above code is meant to work given a function like:

    const playSound = (fileName) => {
      const audio = new Audio();
      audio.src = `path/to/your/audio/${fileName}.mp3`;
      audio.play();
    };
    

    with no need to mention that you need to adjust the relative path path/to/your/audio/ to the desired directory where you have all our audio files. Well, unless you have in the data-audio="" the full path with filename and extension like data-audo="drumset/crash.mp3" in which case you would need only audio.src = fileName; or rather audio.src = pathToFile;