Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
566 views
in Technique[技术] by (71.8m points)

addeventlistener - How to make an image play sound onclick using JavaScript?

So I want to create my 1st project using JS HTLM and CSS, which will be like a drum website ... when I click on an image it should make sound . So, All I know is making a button make sound by clicking on it not an actual image. If you have any idea what should I put in this YYY place ? here's my JS file code : PS : soundi is this image's class

var soundi = document.querySelectorAll(".soundi").length;
 for (var i = 0; i < soundi ; i++) {
   document.querySelectorAll(".soundi")[i].addEventListener("click", function () {
var clickDe = this.YYYY;
switch (clickDe) {
  case "YYYY" :
  var tom1 = new Audio('sounds/tom-1.mp3');
  tom1.play();
    break;

}
   })
 }
question from:https://stackoverflow.com/questions/65643589/how-to-make-an-image-play-sound-onclick-using-javascript

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could add an Id to each image and then register the event listeners like so:

function imageClicked(event) {
    const imgId = event.target.id; // imgId is the name of the instrument => the name of the sound file without the extension
    const soundFile = new Audio(`sounds/${imgId}.mp3`); // this way, you don't have to use a switch statement which can get very long and chaotic
    soundFile.play();
}


document
    .querySelectorAll(".soundi") // querySelectorAll returns all the images so no need to put it in a for loop
    .forEach((img) => img.addEventListener("click", imageClicked));

You will obviously have to choose the image ids properly so that they match up with the file names.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...