YumYumYum YumYumYum - 2 months ago 13
Javascript Question

Javascript - how to play the jplayer from javascript?

I am trying to play the jPlayer with Javascript but it wont play from Javascript i have to manually click the to play it.

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.1.1.slim.min.js"></script>
<script type="text/javascript" src="http://jplayer.org/latest/dist/jplayer/jquery.jplayer.min.js"></script>
<script type="text/javascript">

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

$(document).ready(function(){
$("#jquery_jplayer_1").jPlayer({
ready: function () {
$(this).jPlayer("setMedia", {
title: "Big Buck Bunny",
m4v: "http://www.jplayer.org/video/m4v/Big_Buck_Bunny_Trailer.m4v",
//ogv: "http://www.jplayer.org/video/ogv/Big_Buck_Bunny_Trailer.ogv",
//poster: "http://www.jplayer.org/video/poster/Big_Buck_Bunny_Trailer_480x270.png"
});
},
swfPath: "/js",
supplied: "m4v, ogv",
cssSelectorAncestor: "",
cssSelector: {
title: "#title",
play: "#play",
pause: "#pause",
stop: "#stop",
mute: "#mute",
unmute: "#unmute",
currentTime: "#currentTime",
duration: "#duration"
},
size: {
width: "320px",
height: "180px"
}
});



});
</script>



<style>
div.jp-jplayer {
border:1px solid #009be3;
}
</style>
</head>



<body onload="click_me_to_play();">
<p>
<button id="play">play</button>


</p>
<div id="jquery_jplayer_1" class="jp-jplayer"></div>
</body>
<html>

Answer

Is hacky but worked, on the /jPlayer-2.9.2/examples/blue.monday/demo-01.html fil0e.

function click_me_to_play() {
   setTimeout(function(){ $("#jquery_jplayer_1").jPlayer("play",0); },1000);
}
 // tested on win7 Chrome 51+

I'am still looking why this works and why it doesn't work without the timeout.

Update:
So now I checked it out a bit it, the ready event of the player finishes after the body onload event. So it is only a timing issue. Alternatively you could use the loadeddata event to check if the file is loaded, and then fire the click_me_to_play function, if you want to avoid the setTimeout function, and start playing when the file is loaded.