HTML5 Audio and jQuery

user699242 picture user699242 · Jul 5, 2011 · Viewed 33.2k times · Source

I am trying to use a button to start a track in an HTML5 audio tag using jQuery, but I keep getting an error.

var song = $('#audio');

$('#play').click(function() {
song.play();
});

When I use document.getElementById('audio'), it works, but when using the jQuery selector I get the following error:

Uncaught TypeError: Object [object Object] has no method 'play'

Thanks for any help.

Answer

Darin Dimitrov picture Darin Dimitrov · Jul 5, 2011

Try getting the native DOM element as jQuery knows nothing about .play method on the wrapped array returned by the $('#audio') selector:

song.get(0).play();