JS: add sound in image

Tutorial JS: Add sound in image

Today we will teach you how to click on an image so it emits a sound. First, we need to put the image in a div

<div class=”Nom_Imatge” id=”nomAudio”>

<img src=”img/pajaro_gris.png”>

</div>

Once we have put the image, we just have to link the JS and the sound

<audio src=”ubicaci√≥/de/carpeta” id=”efectes”></audio>

<script src=”ubicaci√≥/carpeta/js “></script>

Next, we will begin to write the JS code. But before that, we will have to do this:

Nom=document.getElementById(“NomAudio”);

Now we will begin to write the function. We want to make it so that when we click on an imatge it triggers an audio sound. To do that, we will have to write the following code:

Nom.addEventListener(“click”,function() {

audioPlay(“NomAudio”);

});

Once we have it written, now is the time to write the function so that the audio is executed when we click on it:

function audioPlay(so) {

var efecte_audio=document.getElementById(“efectes”);

efecte_audio.src=”audio/”+so+”.mp3″;

efecte_audio.play();

}

AND THAT’S IT

NOW YOUR TIME COMES

 

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.