Reputation: 1656
I have a video that I am playing using the YouTubeAPI ( iframe ). An image is in place of the video until the control is clicked to start the video. The image is swapped with the video and the video plays. When the video ends the process is reversed. The problem is I can get the video to restart a second time using my custom control. Here is my code...
<script src="https://www.youtube.com/iframe_api"></script>
<div class="video" id="vid">
<a class="video-control" href="#"></a>
<img id="video-front" src="<?= get_field('video_image') ?>" class="img-responsive" alt="">
<div class="video-container">
<iframe id="player" type="text/html"
src="http://www.youtube.com/embed/G5M721A0b_Q?enablejsapi=1&rel=0&autoplay=1"
frameborder="0"></iframe>
</div>
</div>
<script>
(function($){
//move vid control
vidControlHeight();
$('.video-control').css('left', '-' + wControl + 'px');
$('.video-control').on('click', function(event){
event.preventDefault();
$('#video-front').hide();
$('.video-container').show();
onYouTubeIframeAPIReady();
})
})(jQuery);
function vidControlHeight(){
var hBox = $('#vid').height() / 2,
hControl = $('.video-control').height() / 2,
boxPosition = hBox - hControl;
wControl = $('.video-control').width() / 2;
$('.video-control').css({'left':'-' + wControl + 'px', 'top': boxPosition + 'px'});
}
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady(event) {
event.target.playVideo();
}
function onPlayerStateChange(event) {
if(event.data == YT.PlayerState.ENDED){
$('#video-front').show();
$('.video-container').hide();
}
}
</script>
How can I get the video to replay a second, third, fourth time?
Upvotes: 5
Views: 9708
Reputation: 1656
Although it was calling play, the video was not setting itself back to the beggining. I had to set
player.seekTo(0);
in the onPlayerStateChange() function.
function onPlayerStateChange(event) {
if(event.data == YT.PlayerState.ENDED){
player.seekTo(0);
$('#video-front').show();
$('.video-container').hide();
}
}
https://developers.google.com/youtube/js_api_reference#seekTo
Upvotes: 10
Reputation: 15213
You can add a loop
parameter:
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
},
loop: 1
});
}
https://developers.google.com/youtube/player_parameters#loop
Or you could check in your onPlayerStateChange
if the status is 0
which is when the video has ended and just call event.target.playVideo();
Upvotes: 0