Both of your audio
elements have the same id
, which is not valid HTML because id
attributes "must be unique in the whole document". You should rename the second to something like <audio id="audio_play2">
, and then adjust the second image to be onClick="document.getElementById('audio_play2').play(); return false;"
to reference that audio element instead.
Additionally, you have <source src="<https://www.fesliyanstudios.com/play-mp3/6560>"
where <
and >
shouldn't be included, as well as removing those characters from the src
attribute on the image tags.
Your HTML should be like this (indented for readability):
<audio id="audio_play">
<source
src="https://www.fesliyanstudios.com/play-mp3/6560"
type="audio/mpeg"
/>
</audio>
<img
src="https://www.thesprucepets.com/thmb/KYaXBSM013GnZ2jEZJnX4a9oIsU=/3865x2174/smart/filters:no_upscale()/horse-galloping-in-grass-688899769-587673275f9b584db3a44cdf.jpg"
style="width:156px;height:96px;"
onClick="document.getElementById('audio_play').play(); return false;" />
<audio id="audio_play2">
<source
src="https://www.fesliyanstudios.com/play-mp3/6520"
type="audio/mpeg"
/>
</audio>
<img
src="https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Fupload.wikimedia.org%2Fwikipedia%2Fcommons%2Fthumb%2F2%2F2d%2FHinterwald_Cattle_Hinterzarten.jpg%2F1200px-Hinterwald_Cattle_Hinterzarten.jpg&f=1&nofb=1"
style="width:100px;height:100px;"
onClick="document.getElementById('audio_play2').play(); return false;" />
But if you have many of these image/audio pairs on the page, it's cleaner abstract the HTML/JS by wrapping the pairs in a div and then using class and element selectors to reference the correct audio file instead of adjusting each img's onClick
value. You can use an event listener to automatically link all of your images to their relevant audio element like this:
let wrappers = document.querySelectorAll('.image_audio_wrapper');
wrappers.forEach(function(wrapper) {
let img = wrapper.querySelector('img');
img.addEventListener('click', function() {
let audio = this.parentElement.querySelector('audio');
audio.play();
console.log('playing audio file: ' + audio.querySelector('source').src);
}, false);
});
<div class="image_audio_wrapper">
<audio>
<source
src="https://www.fesliyanstudios.com/play-mp3/6560"
type="audio/mpeg"
/>
</audio>
<img src="https://www.thesprucepets.com/thmb/KYaXBSM013GnZ2jEZJnX4a9oIsU=/3865x2174/smart/filters:no_upscale()/horse-galloping-in-grass-688899769-587673275f9b584db3a44cdf.jpg" style="width:156px;height:96px;" />
</div>
<div class="image_audio_wrapper">
<audio>
<source
src="https://www.fesliyanstudios.com/play-mp3/6520"
type="audio/mpeg"
/>
</audio>
<img src="https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Fupload.wikimedia.org%2Fwikipedia%2Fcommons%2Fthumb%2F2%2F2d%2FHinterwald_Cattle_Hinterzarten.jpg%2F1200px-Hinterwald_Cattle_Hinterzarten.jpg&f=1&nofb=1" style="width:100px;height:100px;"
/>
</div>