Enhancements for jPlayer Implementation

By Forrest Smith - Drempd.com

I love the jPlayer for easily being able to add modern mp3 support to web pages.  I wanted a few additional features, so I created this additional script which adds a few updated features:

  • Adding rewind/fast-forward support
  • Ability to toggle the volume controls on and off
  • Ability to specify the mp3 url by setting a ‘data-audiourl’ paramter.

The code for the additional javascript:

$(function () {

	$('.jp-jplayer').each(function (i, obj) {

		var jplayerId = "#" + $(this).attr('id');

		$(jplayerId).jPlayer({
			ready: function () {

				var audioUrl = $(this).attr('data-audiourl');
				
				$(this).jPlayer("setMedia", {
					mp3: audioUrl
				});
			},
			play: function () { // To avoid multiple jPlayers playing together.
				
				$(this).jPlayer("pauseOthers");
			},
			swfPath: "/js/vendor/",
			supplied: "mp3",
			wmode: "window",
			globalVolume: true,
			useStateClassSkin: true,
			autoBlur: false,
			smoothPlayBar: true,
			keyEnabled: true,
			cssSelectorAncestor: jplayerId + "_container",
		});

	});

	$(document).on('click', '.jp-play', function (e) {
		e.preventDefault();
		$(this).find('.fa-playpause').toggle();
	});

	$(document).on('click', '.jp-volume-controls-toggle', function (e) {
		e.preventDefault();
		var target = "#" + $(this).attr('data-target');
		$(target).toggle();
	});

	$(document).on('click', '.jp-back', function (e) {
		e.preventDefault();
		JpSeek($(this), -10);
	});

	$(document).on('click', '.jp-forward', function (e) {
		e.preventDefault();
		JpSeek($(this), 10);
	});

});

$(document).mouseup(HideVolume);




function HideVolume(e) {
	var container = $(".jp-volume-controls");
	
	// if the target of the click isn't the container nor a descendant of the container, and if
	if (!container.is(e.target) && container.has(e.target).length === 0 && container.is(':visible') && !$(e.target).hasClass('volume-toggle')) {
		container.hide();
	}
}

function JpSeek(el, val) {

	var playerId = el.closest('.jp-audio').attr('id').replace("_container", "");

	var jPlayerInstance = $("#" + playerId);
	var currentpos = jPlayerInstance.data("jPlayer").status.currentTime;
	var songDuration = jPlayerInstance.data("jPlayer").status.duration;
	var currentPosPercentage = currentpos / songDuration * 100;

	jPlayerInstance.jPlayer("playHead", currentPosPercentage + val); // Move play-head.
}

HTML Code

Listen to this phone lead: