Starting a Vimeo embed at a given timestamp using the JS API

Vimeo by far provides the best hosted video embed service out there by far, in my opinion. This post explains how to change the behavior of a Vimeo embed to skip to a given timestamp when the user plays the video. We’ll use data attributes to store the start time in the HTML.

Why would I want this?

In my situation, the college I work at runs a robust news site that often times includes videos. In that context, we format our videos to include an opening branding screen, then a brief intro paragraph to orient people to the video they are about to watch. This works great for the news site, but what if we come across a situation where we want to skip that intro and go right into the video?

Vimeo Player JavaScript API to the rescue

The Vimeo Player JS API allows developers to easily interact with their Vimeo embeds. The directions on including it are pretty straight forward, they even offer a CDN hosted version to include:

<iframe src="https://player.vimeo.com/video/208129791" width="500" height="281" frameborder="0" webkitallowfullscreen="" mozallowfullscreen="" allowfullscreen=""></iframe>

Next, we look for our Vimeo Player in our JavaScript. In my example, our Vimeo videos are put into our site as follows:


<div class="video" data-start-time="5">
  <iframe src="https://player.vimeo.com/video/204427616?color=498957&title=0&byline=0&portrait=0" width="640" height="360" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
</div>

So, to access this Vimeo embed, in my JavaScript file I do something like:

if ($('div.video').length) {
  
  // Loop through all the videos
  $('div.video').each(function( index, value ) {

    // Grab the Vimeo player already on the page
    var vPlayer = new Vimeo.Player($(this).find('iframe')[0]);

    // Set a flag to determine if the player has been paused yet
    var pause = false;

    vPlayer.on('play', function() {

      // If the player has not yet been paused, start it at
      // the specified time indicated in data-start-time
      if (!pause)
        vPlayer.setCurrentTime($(value).attr('data-start-time'));
      });

    vPlayer.on('pause', function() {
      // Set the pause flag to true. Setting this prevents
      // the player from starting the video at 
      // the 'data-start-time' instead of just 
      // continuing the video where it was paused.
      pause = true;
    });
  });
}

Limitations

There’s nothing to stop people from rewinding back to the beginning and watching the intro if they choose, so if you’re trying to use this method to cut some video, it won’t work.

This also assumes you have the means to add data attributes to your HTML to store your start times. If you don’t have access to your HTML, you might need to rethink your approach.


Worked perfectly for my needs, hope it helps!

What do you think?