skip to Main Content

using javascript, i want to play a different sound on the click of an image. i have this code, how to modify to let the onclick attribute set the mp3 file i want to play?

i have this:

function play(){
    var audio = new Audio("sounds/apple.mp3");
    audio.play();
}

<img onclick="play()" src="images/apple.png" width="400" height="400" /><br />

but lets say i want orange and pear?

i could repeat the play function for each image but that would be to much code.

2

Answers


  1. For that I would suggest to use only one function play which gonna take an argument path is mp3 path:

    JS

    function play(path){
        var audio = new Audio(path);
        audio.play();
    }
    

    HTML

    <img onclick="play('sounds/apple.mp3')" src="images/apple.png" width="400" height="400" /><br />
    <img onclick="play('sounds/orange.mp3')" src="images/orange.png" width="400" height="400" />
    
    Login or Signup to reply.
  2. onclick should be avoided since generally speaking JS should be in one place only, and that’s the respective tag or file. Use addEventListener() instead.
    You could store your mp3 filename in a data-* attribute:

    const play = name => new Audio(`sounds/${name}.mp3`).play();
    
    document.querySelectorAll("[data-audio]").forEach(el => {
      el.addEventListener("click", () => {
        play(el.dataset.audio);
      });
    });
    
    <img data-audio="apple" src="images/apple.png" alt="apple" />
    <img data-audio="orange" src="images/orange.png" alt="orange" />
    <img data-audio="pear" src="images/pear.png" alt="pear" />
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search