Using the YouTube iFrame API

This is going to try to show you how to use the YouTube iFrame API along with Marketo.  I had some challenges with the documentation so what I’m including below is that works well for me.

For more info, please read the official documentation.

Step 1:

Place this code where you want the video to exist:

 <div id="player"></div>

Now, from here it gets tricky so follow along:

// 2. This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

The part above calls in the scripts needed.

// 3. This function creates an <iframe> (and YouTube player)
// after the API code downloads.

var player;

function onYouTubeIframeAPIReady() {
 player = new YT.Player('player', {
 videoId: '{{my.youtube-video-id}}',
 height: '390',
 width: '640',
 events: {
 'onReady': onPlayerReady,
 'onStateChange': onPlayerStateChange
 }
 });
}

The section above first creates a player, the loads in the video ID.  This is visible in the URL of the video on YouTube or if you use the “Embed” function to share the video.  I like tokening it so that I can clone the program and not create a new template. Also, in here we define some events. onReady will call the onPlayerReady function and onStateChange till call the onPlayerStateChange function.

// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
 event.target.playVideo();
}

/** YouTube API
 -1 (unstarted)
 0 (ended)
 1 (playing)
 2 (paused)
 3 (buffering)
 5 (video cued)
 **/

In the first function above, all we do is play the video but this would give you an opportunity to put in any additional code you’d like to fire when the video is ready. In the case, when the video is ready we play the video.

Now, the part with the numbers and event names is important. This gives you the opportunity to define what happens at each of these specific events, such as once the video goes from unstarted to playing, etc.

function onPlayerStateChange(event) {
 if ((event.data === 2) && (showModalAgain != 0)) {
 showModal();
 }
}

In here, I state that if someone pauses the video (event.data === 2) AND there’s a variable called showModalAgain that’s not set to 0 then run a function called “Show Modal.”

See my next post on the Modal.

Leave a Reply

Your email address will not be published. Required fields are marked *