HTML5 Audio and jQuery

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.

Answers


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();

You can also write it like song.trigger('play');. That will allow you to use the $('#audio'); selector.


Instead of .get() just use object notation:

var song = $('#audio');

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

It's less to type :)


Need Your Help

What are the best practices for SQLite on Android?

android database sqlite

What would be considered the best practices when executing queries on an SQLite database within an Android app?

Django: How to make a datetime object aware of the timezone in which it was created?

python django datetime django-models timezone

I am running a program that requests ocean tide data from a remote server. The time and date of this tide data is being computed based on my machine's local time zone. I want to use these local dat...