Friends,
I’m basically trying to build a simple audio player that grabs the id of the image clicked and plays the corresponding audio file. Here’s where I’m at… with no luck.
I have been trying to find an elegant way to do this for hours and would be most grateful for some help!
Thanks!
<script type="text/javascript">
$(function() {
$(".playback").click(function(){
var selectedAudio = $(this).attr("id");
var myAudio = document.getElementById(selectedAudio);
myAudio.play();
});
</script>
<body>
<audio id="boardroom" preload="auto"><source src="boardroom.mp3" type="audio/mpeg" /></audio>
<audio id="bathroom" preload="auto"><source src="bathroom.mp3" type="audio/mpeg" /></audio>
<audio id="livingroom" preload="auto"><source src="livingroom.mp3" type="audio/mpeg" /></audio>
<img class="playback" id="boardroom" src="images/audio.png">
</body
2 things.
Never, ever, use the same
idon more than one element in your document. They are supposed to be unique, and bad stuff can happen when they are not unique. In your case, your image and your audio element share the same id, this is BAD. How willdocument.getElementByIdknow which element to find if more than one share an ID? You need to make them different, though you can still use one to find the other.<img id="somename">and<audio id="somename-audio">, for instance.The audio source in your fiddle didn’t point to an audio file. It pointed to a webpage about the audio file. I fixed the link to point to the actual audio file.
Working version: http://jsfiddle.net/Pzsax/2/
Html:
JS:
Or since you seem to be using jQuery, that could simply be:
Lastly, rather than relying on id’s to pass arund meaningful data, perhaps data attributes might be a cleaner approach, allowing you to encode bits of data, like names of sounds, in the buttons that play them.