Reputation: 13
I have a very simple javascript function to play and pause an HTML audio file. From testing I can tell that the below function works perfectly when I use document.getElementById, but when I try to use jQuery the .paused is undefined.
function playAudio(audioID){
var clip = $("#" + audioID);
console.log(clip);
console.log(clip.paused);
if (clip.paused){
clip.play();
}
else{
clip.pause();
}
}
This is called by an onclick call:
<img src="media/play.png" class="play" onclick="playAudio('audio1');">
When I log clip, it returns the proper audio file. But when I try to log if paused is true or false, the console says that it is undefined.
Any suggestions?
Thanks.
Upvotes: 1
Views: 1240
Reputation: 97672
$("#" + audioID)
does not give you the audio element like document.getElementById
would, it gives you a jQuery object which encapsulates the audio element.
If you want to access the properties of the audio element you will have to expose it from the jQuery object.
To expose a property from the jQuery object you can use .prop()
(if (clip.prop('paused')){
), you can also expose the element itself with .get()
and []
function playAudio(audioID){
var clip = $("#" + audioID);
console.log(clip[0]);
console.log(clip.prop('paused'));
if (clip.prop('paused')){
clip[0].play();
}
else{
clip.get(0).pause();
}
}
Upvotes: 2