i’m trying to create a script so that when you click on the picture A, the picture B appears instead and when you click again the image A appears, etc.
It works just fine but i’d like to add to it a music when you click on the picture A so that it plays when the picture B is displayed.
function changeImage() {
if (document.getElementById("imgClickAndChange").src == "https://www.shutterstock.com/image-photo/surreal-image-african-elephant-wearing-260nw-1365289022.jpg") {
document.getElementById("imgClickAndChange").src = "https://thumbs.dreamstime.com/b/belle-for%C3%AAt-tropicale-%C3%A0-l-itin%C3%A9raire-am%C3%A9nag%C3%A9-pour-amateurs-de-la-nature-de-ka-d-ang-36703721.jpg";
} else {
document.getElementById("imgClickAndChange").src = "https://www.shutterstock.com/image-photo/surreal-image-african-elephant-wearing-260nw-1365289022.jpg";
}
}
<p>
<img alt="" src="https://www.shutterstock.com/image-photo/surreal-image-african-elephant-wearing-260nw-1365289022.jpg" style="height: 85px; width: 198px" id="imgClickAndChange" onclick="changeImage()" />
</p>
3
Answers
Keep in mind that audio and video must be muted as per browser permission rules since 2018.
In other words you can’t play sounds unless the user clicks the player.
https://developer.chrome.com/blog/autoplay/#web-audio
But you probably don’t want to have a visible audio player and to just play the music as you please, but you can’t unless its visible and muted…
Is this what you want:
Here I updated your code, I used the
HTML5
audio element and on thechangeImage
function I play the sound file on every image change.Thanks for asking this. I hope my answer will help you to reach your desired output.
Kindly check my code on codepen.