Multiple JPlayers on the same page

JPlayer is a very nice Javascript library that allows you to create HTML5 media players in your HTML pages.

http://www.jplayer.org/

The site creates pretty decent documentation and examples, but I recently came to a dead halt when I had to create multiple audio players on the same page.

The JPlayer site provides an example of this, but it isn’t exactly clear how it works. This post explains exactly what you have to do.

First thing to understand:

In HTML5, when you want to create a media player, you either use the default interface or create a custom interface. If you want to create a custom interface, you have to create separate HTML for the interface. The default JPlayer installation includes a custom interface, so if you want to create multiple players, you have to create multiple interfaces, each of which must be carefully constructed from the point of view of the DOM and CSS.

Each of your interfaces will have a DOM Element ID, which of course must be unique. That ID determines which players activates when a control in that interface is clicked (play, stop, pause etc). If you don’t have this correctly set up, either multiple players will start at once, or nothing will happen at all.

If you only create one player on a page, the default Interface Element ID that JPlayer looks for is “#jp_interface_1″.

If you want to create multiple players, you need to tell each JPlayer instance which interface it is associated with.

To do this, you specify the cssSelectorAncestor property for each player instance you create:

eg

function js_audioPlayer(file,location) {
	jQuery("#jquery_jplayer_" + location).jPlayer( {
	    ready: function () {
	      jQuery(this).jPlayer("setMedia", {
		mp3: file
	      });
	    },
	    cssSelectorAncestor: "#jp_interface_" + location,
	    swfPath: "/swf"
	  });
return;
}

In this example, I’m passing a file and location variable into a wrapper function, which then constructs the player.

In my script, I dynamically create Player DIVs with IDs:

jquery_jplayer_1
jquery_jplayer_2
jquery_jplayer_3
etc

and Interface DIVs with IDs:

jp_interface_1
jp_interface_2
jp_interface_3
etc

and then run the js_audioPlayer() javascript function as many times as I want players:

js_audioPlayer(‘file1.mp3′,1);
js_audioPlayer(‘file2.mp3′,2);
js_audioPlayer(‘file3.mp3′,3);
etc

More: http://www.jplayer.org/latest/developer-guide/#jPlayer-predefined-css-selectors

3 thoughts on “Multiple JPlayers on the same page

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>