How to control a video with JavaScript

Streaming services such as YouTube or Vimeo offer us a way to host videos and embed it directly at any website for free. The player that’s being offered is full of bells and whistles however, sometimes we want it to do (or not to do) something else. Let’s see how this can be accomplished.

First of all, get yourself a video


It’s assumed that you know basics of HTML and JavaScript as we will focus purely on implementation here.


To start, let’s get a hand on a video. This one is as good as any other: 



Every video hosted has some sort of an ID at the streaming platform. It can be often found at the URL. In our case this is it: vimeo.com/channels/staffpicks/488734703


Get Vimeo API

The second key ingredient that will help us to capture and modify events sent to and from the video (iframe) is the Vimeo’s library. Under that link you will find different methods on how to get a hold of it and embed it to your HTML document or application. I also use JQuery since it’s usually available at most of the websites I work with.

Basic interactions with the video iframe

Recently, I had to code following behaviours:


  1. Auto-play the video wrapped up within a pop-up window.
  2. Stop the video when pop-up was closed

I could not simply rely on basic (yet amazing) player provided by Vimeo. Instead we have to find a way to communicate with the iframe.

In the following code snippet you can see how you can control the video via custom buttons that have: play, pause and mute events attached. Full code sample can be found here as gist.


Here is a working example via jsfiddle.

As you can see we have taken the power over the iframe. Analogically, we can assign and catch any type of events, send options to the player and back.


Thanks for getting this far!


Good luck with your next project and let me know if you have any questions.


Cheers
Damian

Leave a comment

Yay! You've decided to leave a comment. That's fantastic! Please keep in mind that * marked fields are mandatory, comments are moderated and rel="nofollow" is in use. So, please do not use a spammy keywords or a domain as your name, or else it will be deleted.

Let's have a personal and meaningful conversation instead. Thanks for dropping by!