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
For that I would suggest to use only one function
play
which gonna take an argumentpath
is mp3 path:JS
HTML
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 adata-*
attribute: