Reputation: 51
I am trying to figure out a way to trigger a javascript modal popup/popover when a YouTube video finishes.
I first saw this achieved on UpWorthy.com. See this video for an example when the video ends: http://www.upworthy.com/bully-calls-news-anchor-fat-news-anchor-destroys-him-on-live-tv
I have enabled the javascript api by adding the JS parameter to the embed code (enablejsapi=1)
I am using this Simple Modal script to achieve the modal: http://www.ericmmartin.com/projects/simplemodal/
How do I get the end of the youtube video to trigger it?
Many thanks
Upvotes: 3
Views: 3224
Reputation: 51
<html>
<head>
<title>YT Test</title>
<script type="text/javascript">
<!--
// 2. This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "http://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// 3. This function creates an <iframe> (and YouTube player) after the API code downloads.
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: 'ecccag3L-yw',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
// The API will call this function when the video player is ready.
function onPlayerReady(event) { /* do nothing yet */ }
// The API calls this function when the player's state changes.
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.ENDED) {
// insert appropriate modal (or whatever) below
alert('I hope you enjoyed the video')
}
}
-->
</script>
</head>
<body>
<div id="player"></div>
</body>
<html>
Upvotes: 2
Reputation: 4585
Use the onStateChange
event of the Youtube Player and check the current player state. If the state is YT.PlayerState.ENDED
then you can trigger the modal dialog box.
From Youtube JavaScript player api reference document(with some modification)
function onYouTubePlayerReady(playerId) {
ytplayer = document.getElementById(playerId);
ytplayer.addEventListener("onStateChange", "onytplayerStateChange");
}
function onytplayerStateChange(newState) {
if(newState==YT.PlayerState.ENDED){
//OPEN Modal dialog box here
}
}
Upvotes: 0