Reputation: 691
I am using the Youtube API in order to generate a video using the following example:
HTML:
<div id="player"></div>
Javascript:
<script src="http://www.youtube.com/player_api"></script>
<script>
// create youtube player
var player;
function onYouTubePlayerAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: '0Bmhjf0rKe8',
events: {
onReady: onPlayerReady,
onStateChange: onPlayerStateChange
}
});
}
// autoplay video
function onPlayerReady(event) {
}
// when video ends
function onPlayerStateChange(event) {
if(event.data === 0) {
alert('done');
}
}
</script>
This code is based on the following question:
How to detect when a youtube video finishes playing?
The only difference is that I have deleted the "onPlayerReady" function since I don't want this video to be autoplayed automatically. So, I would like this video to be played using an external link using the following Javascript:
$(document).ready(function() {
$('#play-video').on('click', function(ev) {
$("#player")[0].src += "&autoplay=1";
ev.preventDefault();
});
});
And the following HTML code:
<a id="play-video" href="#">Play Video</a>
When executed, the video plays when the link is clicked. However, at the end of the video, an alert should popup notifying that the video ended.
This alert ONLY shows up if the video is played from the default Youtube play button in the center of the video. However, if played through the "play-video" link it the alert doesn't show up.
Any ideas of what I could be missing?
Thanks!
Upvotes: 1
Views: 1452
Reputation: 773
Hey what you can do is call player's inbuilt api playVideo()
method on your play video link. Refer Youtube API guide.
What I have changed is your play video link click listener to this and it gives me expected result as you would require.
$('#play-video').on('click', function(ev) {
if(player){
player.playVideo();
}
ev.preventDefault();
});
Please find demo for the same https://codepen.io/samarthsinha/pen/ZKBBqM
Upvotes: 0
Reputation: 3480
Try this.
$(document).ready(function() {
$('#play-video').on('click', function(ev) {
$("#player")[0].src += "&autoplay=1";
onYouTubePlayerAPIReady();
ev.preventDefault();
});
});
Upvotes: 0
Reputation: 1683
For checking if the video has finished playing, you can do this.
player.addEventListener("onStateChange", function(state){
if(state === 0){
// video has finished playing
}
});
Upvotes: 1