Create Custom Video Player Controls with CanJS

July 30, 2018 0 Comments

Create Custom Video Player Controls with CanJS

 

 

In this guide, you will learn how to create a custom video player using the <video> element and CanJS. The custom video player will:

  • Have custom play and pause buttons.
  • Show the current time and duration of the video.
  • Have a <input type="range"> slider that can adjust the position of the video.

The final player looks like:

The following sections are broken down into the following parts:

  • The problem — A description of what the section is trying to accomplish.
  • What you need to know — Browser or CanJS APIs that are useful for solving the problem.
  • The solution — The solution to the problem.

Setup

START THIS TUTORIAL BY Forking THE FOLLOWING CodePen:

Click the Edit in CodePen button. The CodePen will open in a new window. Click the Fork button.

This CodePen:

  • Creates a <video> element that loads a video. Right click and select “Show controls” to see the video’s controls.
  • Loads CanJS's custom element library: Component.

The problem

In this section, we will:

  • Create a custom <video-player> element that takes a src attribute and creates a <video> element within itself. We should be able to create the video like:

    <video-player src:raw="http://bit.ly/can-tom-n-jerry">; </video-player>
  • The embedded <video> element should have the native controls enabled.

When complete, the result will look exactly the same as the player when you started. The only difference is that we will be using a custom <video-player> element in the HTML tab instead of the native <video> element.

What you need to know

To set up a basic CanJS application (or widget), you define a custom element in JavaScript and use the custom element in your page’s HTML.

To define a custom element, extend Component with a tag that matches the name of your custom element. For example:

Component.extend({ tag: "video-player" })

Then you can use this tag in your HTML page:

<video-player></video-player>

But this doesn’t do anything ... yet. Components add their own HTML through their view property:

Component.extend({ tag: "video-player", view: &lt;h2&gt;I am a player!&lt;/h2&gt; });

A component’s view is rendered with its ViewModel. For example, we can make a <video> display "http://bit.ly/can-tom-n-jerry" by defining a src property on the ViewModel and using it in the view like:

Component.extend({ tag: "video-player", view: &lt;video&gt; &lt;source src=&quot;{{src}}&quot;/&gt; &lt;/video&gt;, ViewModel: { src: {type: "string", default: "http://bit.ly/can-tom-n-jerry"} } });

But we want the <video-player> to take a src attribute value itself and use that for the <source>’s src. For example, if we wanted the video to play "http://dl3.webmfiles.org/big-buck-bunnytrailer.webm" instead of "http://bit.ly/can-tom-n-jerry", we would:

  1. Update <video-player> to pass "http://dl3.webmfiles.org/big-buck-bunnytrailer.webm" with toChild:raw:
    <video-player src:raw="http://dl3.webmfiles.org/big-buck-bunny_trailer.webm"/>;
  2. Update the ViewModel to define a src property like:
    Component.extend({ tag: "video-player", view: &lt;video&gt; &lt;source src=&quot;{{src}}&quot;/&gt; {{!&#x1F440;}} &lt;/video&gt;, ViewModel: { src: "string" } });

Finally, to have a <video> element show the native controls, add a controls attribute like:

<video controls>

The solution

Update the JS tab to:

import {Component} from "//unpkg.com/can@5/core.mjs"; Component.extend({ //👀 tag: "video-player", //👀 view: {{!&#x1F440;}} &lt;video controls&gt; {{!&#x1F440;}} &lt;source src=&quot;{{src}}&quot;/&gt; {{!&#x1F440;}} &lt;/video&gt; {{!&#x1F440;}}, //👀 ViewModel: { //👀 src: "string", //👀 } //👀 }); //👀 

Update the HTML to:

<video-player src:raw="http://bit.ly/can-tom-n-jerry"></video-player>; <!--👀-->

Make play / pause button change as video is played and paused

The problem

When the video is played or paused using the native controls, we want to change the content of a <button> to say “Play” or “Pause”.

When the video is played, the button should say “Pause”. When the video is paused, the button should say “Play”.

We want the button to be within a <div> after the video element like:

</video> <div> <button>Play</button> </div>

What you need to know

  • To change the HTML content of the page, use {{#if(expression)}} and {{else}} like:

    <button>{{#if(playing)}} Pause {{else}} Play {{/if}}</button>
  • The view responds to values in the ViewModel. To create a boolean value in the ViewModel do:

    ViewModel: { // ... playing: "boolean", }
  • Methods can be used to change the ViewModel. The following might create methods that change the playing value:

    ViewModel: { // ... play() { this.playing = true; }, pause() { this.playing = false; }, }
  • You can listen to events on the DOM with on:event. For example, the following might listen to a click on a <div> and call doSomething():

    <div on:click="doSomething()">

    <video> elements have a variety of useful events, including play and pause events that are emitted when the video is played or paused.

The solution

Update the JavaScript tab to:

import {Component} from "//unpkg.com/can@5/core.mjs"; Component.extend({ tag: "video-player", view: &lt;video controls on:play=&quot;play()&quot; {{!&#x1F440;}} on:pause=&quot;pause()&quot;&gt; {{!&#x1F440;}} &lt;source src=&quot;{{src}}&quot;/&gt; &lt;/video&gt; &lt;div&gt; {{!&#x1F440;}} &lt;button&gt; {{!&#x1F440;}} {{#if(playing)}} Pause {{else}} Play {{/if}} {{!&#x1F440;}} &lt;/button&gt; {{!&#x1F440;}} &lt;/div&gt; {{!&#x1F440;}}, ViewModel: { src: "string", playing: "boolean", //👀 play() { //👀 this.playing = true; //👀 }, //👀 pause() { //👀 this.playing = false; //👀 }, //👀 } }); 

Make clicking the play/pause button play or pause the video

The problem

When the play/pause <button> we created in the previous section is clicked, we want to either play or pause the video.

What you need to know

CanJS prefers to manage the state of your application in ViewModel. The <video> player has state, such as if the video is playing. When the play/pause button is clicked, we want to update the state of the ViewModel and have the ViewModel update the state of the video player as a side effect.

What this means is that instead of something like:

togglePlay() { if ( videoElement.paused ) { videoElement.play() } else { videoElement.pause() } }

We update the state like:

togglePlay() { this.playing = !this.playing; }

And listen to when playing changes and update the video element like:

viewModel.listenTo("playing", function(event, isPlaying) { if ( isPlaying ) { videoElement.play() } else { videoElement.pause() } })

This means that you need to:

  1. Listen to when the <button> is clicked and call a ViewModel method that updates the playing state.
  2. Listen to when the playing state changes and update the state of the <video> element.

You already know everything you need to know for step #1. (Have the button call a togglePlay method with on:click="togglePlay()" and make the togglePlay() method toggle the state of the playing property.)

For step #2, you need to use the connectedCallback lifecycle hook. This hook gives you access to the component’s element and is a good place to do side-effects. Its use looks like this:

ViewModel: { // ... connectedCallback(element) { // perform mischief } }

connectedCallback gets called once the component’s element is in the page. You can use listenTo to listen to changes in the ViewModel’s properties and perform side-effects. The following listens to when playing changes:

ViewModel: { // ... connectedCallback(element) { this.listenTo("playing", function(event, isPlaying) { }) } }

Use querySelector to get the <video> element from the <video-player> like:

element.querySelector("video")

<video> elements have a .play() and .pause() methods that can start and stop a video.

The solution

Update the JavaScript tab to:

import {Component} from "//unpkg.com/can@5/core.mjs"; Component.extend({ tag: "video-player", view: &lt;video controls on:play=&quot;play()&quot; on:pause=&quot;pause()&quot;&gt; &lt;source src=&quot;{{src}}&quot;/&gt; &lt;/video&gt; &lt;div&gt; &lt;button on:click=&quot;togglePlay()&quot;&gt; {{!&#x1F440;}} {{#if(playing)}} Pause {{else}} Play {{/if}} &lt;/button&gt; &lt;/div&gt;, ViewModel: { src: "string", playing: "boolean", play() { this.playing = true; }, pause() { this.playing = false; }, togglePlay() { //👀 this.playing = !this.playing; //👀 }, //👀 connectedCallback(element) { //👀 this.listenTo("playing", function(event, isPlaying) { //👀 if (isPlaying) { //👀 element.querySelector("video").play(); //👀 } else { //👀 element.querySelector("video").pause(); //👀 } //👀 }); //👀 } //👀 } }); 

Show current time and duration

The problem

Show the current time and duration of the video element. The time and duration should be formatted like: mm:SS. They should be presented within two spans like:

</button> <span>1:22</span> <span>2:45</span>

What you need to know

  1. Methods can be used to format values in can-stache. For example, you can uppercase values like this:

    <span>{{upper(value)}}</span>

    With a method like:

    ViewModel: { // ... upper(value) { return value.toString().toUpperCase(); } }

    The following can be used to format time:

    formatTime(time) { if (time = null || time = undefined) { return "--"; } const minutes = Math.floor(time / 60); let seconds = Math.floor(time - minutes * 60); if (seconds < 10) { seconds = "0" + seconds; } return minutes + ":" + seconds; }
  2. Time is given as a number. Use the following to create a number property on the ViewModel:

    ViewModel: { // ... duration: "number", currentTime: "number" }
  3. <video> elements emit a loadmetadata event when they know how long the video is. They also emit a timeupdate event when the video’s current play position changes.

    • videoElement.duration reads the duration of a video.
    • videoElement.currentTime reads the current play position of a video.
  4. You can get the element in an stache on:event binding with scope.element like:

    <video on:timeupdate="updateTimes(scope.element)"/>

The solution

Update the JavaScript tab to:

import {Component} from "//unpkg.com/can@5/core.mjs"; Component.extend({ tag: "video-player", view: &lt;video controls on:play=&quot;play()&quot; on:pause=&quot;pause()&quot; on:timeupdate=&quot;updateTimes(scope.element)&quot; {{!&#x1F440;}} on:loadedmetadata=&quot;updateTimes(scope.element)&quot;&gt; {{!&#x1F440;}} &lt;source src=&quot;{{src}}&quot;/&gt; &lt;/video&gt; &lt;div&gt; &lt;button on:click=&quot;togglePlay()&quot;&gt; {{#if(playing)}} Pause {{else}} Play {{/if}} &lt;/button&gt; &lt;span&gt;{{formatTime(currentTime)}}&lt;/span&gt; / {{!&#x1F440;}} &lt;span&gt;{{formatTime(duration)}} &lt;/span&gt; {{!&#x1F440;}} &lt;/div&gt;, ViewModel: { src: "string", playing: "boolean", duration: "number", //👀 currentTime: "number", //👀 updateTimes(videoElement) { //👀 this.currentTime = videoElement.currentTime || 0; //👀 this.duration = videoElement.duration; //👀 }, //👀 formatTime(time) { //👀 if (time = null || time = undefined) { //👀 return "--"; //👀 } //👀 const minutes = Math.floor(time / 60); //👀 let seconds = Math.floor(time - minutes * 60); //👀 if (seconds < 10) { //👀 seconds = "0" + seconds; //👀 } //👀 return minutes + ":" + seconds; //👀 }, //👀 play() { this.playing = true; }, pause() { this.playing = false; }, togglePlay() { this.playing = !this.playing; }, connectedCallback(element) { this.listenTo("playing", function(event, isPlaying) { if (isPlaying) { element.querySelector("video").play(); } else { element.querySelector("video").pause(); } }); } } }); 

Make range show position slider at current time

The problem

Create a <input type="range"/> element that changes its position as the video playing position changes.

The <input type="range"/> element should be after the <button> and before the currentTime span like:

</button> <input type="range"/> <span>{{formatTime(currentTime)}}</span> /

What you need to know

  • The range input can have an initial value, max value, and step size specified like:

    <input type="range" value="0" max="1" step="any"/>
  • The range will have values from 0 to 1. We will need to translate the currentTime to a number between 0 and 1. We can do this with a computed getter property like:

    ViewModel: { // ... get percentComplete() { return this.currentTime / this.duration; }, }
  • Use key:from to update a value from a ViewModel property like:

    <input value:from="percentComplete"/>

The solution

Update the JavaScript tab to:

import {Component} from "//unpkg.com/can@5/core.mjs"; Component.extend({ tag: "video-player", view: &lt;video controls on:play=&quot;play()&quot; on:pause=&quot;pause()&quot; on:timeupdate=&quot;updateTimes(scope.element)&quot; on:loadedmetadata=&quot;updateTimes(scope.element)&quot;&gt; &lt;source src=&quot;{{src}}&quot;/&gt; &lt;/video&gt; &lt;div&gt; &lt;button on:click=&quot;togglePlay()&quot;&gt; {{#if(playing)}} Pause {{else}} Play {{/if}} &lt;/button&gt; &lt;input type=&quot;range&quot; value=&quot;0&quot; max=&quot;1&quot; step=&quot;any&quot; {{!&#x1F440;}} value:from=&quot;percentComplete&quot;/&gt; {{!&#x1F440;}} &lt;span&gt;{{formatTime(currentTime)}}&lt;/span&gt; / &lt;span&gt;{{formatTime(duration)}} &lt;/span&gt; &lt;/div&gt;, ViewModel: { src: "string", playing: "boolean", duration: "number", currentTime: "number", get percentComplete() { //👀 return this.currentTime / this.duration; //👀 }, //👀 updateTimes(videoElement) { this.currentTime = videoElement.currentTime || 0; this.duration = videoElement.duration; }, formatTime(time) { if (time = null || time = undefined) { return "--"; } const minutes = Math.floor(time / 60); let seconds = Math.floor(time - minutes * 60); if (seconds < 10) { seconds = "0" + seconds; } return minutes + ":" + seconds; }, play() { this.playing = true; }, pause() { this.playing = false; }, togglePlay() { this.playing = !this.playing; }, connectedCallback(element) { this.listenTo("playing", function(event, isPlaying) { if (isPlaying) { element.querySelector("video").play(); } else { element.querySelector("video").pause(); } }); } } }); 

The problem

In this section we will:

  • Remove the native controls from the video player. We don’t need them anymore!
  • Make it so when a user moves the range slider, the video position updates.

What you need to know

Similar to when we made the play/pause button play or pause the video, we will want to update the currentTime property and then listen to when currentTime changes and update the <video> element’s currentTime as a side-effect.

This time, we need to translate the sliders values between 0 and 1 to currentTime values. We can do this by creating a percentComplete setter that updates currentTime like:

ViewModel: { // ... get percentComplete() { return this.currentTime / this.duration; }, set percentComplete(newVal) { this.currentTime = newVal * this.duration; }, // ... }

Use key:bind to two-way bind a value to a ViewModel property:

<input value:bind="someViewModelProperty"/>

The solution

Update the JavaScript tab to:

import {Component} from "//unpkg.com/can@5/core.mjs"; Component.extend({ tag: "video-player", view: &lt;video {{!&#x1F440;}} on:play=&quot;play()&quot; on:pause=&quot;pause()&quot; on:timeupdate=&quot;updateTimes(scope.element)&quot; on:loadedmetadata=&quot;updateTimes(scope.element)&quot;&gt; &lt;source src=&quot;{{src}}&quot;/&gt; &lt;/video&gt; &lt;div&gt; &lt;button on:click=&quot;togglePlay()&quot;&gt; {{#if(playing)}} Pause {{else}} Play {{/if}} &lt;/button&gt; &lt;input type=&quot;range&quot; value=&quot;0&quot; max=&quot;1&quot; step=&quot;any&quot; value:bind=&quot;percentComplete&quot;/&gt; {{!&#x1F440;}} &lt;span&gt;{{formatTime(currentTime)}}&lt;/span&gt; / &lt;span&gt;{{formatTime(duration)}} &lt;/span&gt; &lt;/div&gt;, ViewModel: { src: "string", playing: "boolean", duration: "number", currentTime: "number", get percentComplete() { return this.currentTime / this.duration; }, set percentComplete(newVal) { //👀 this.currentTime = newVal * this.duration; //👀 }, //👀 updateTimes(videoElement) { this.currentTime = videoElement.currentTime || 0; this.duration = videoElement.duration; }, formatTime(time) { if (time = null || time = undefined) { return "--"; } const minutes = Math.floor(time / 60); let seconds = Math.floor(time - minutes * 60); if (seconds < 10) { seconds = "0" + seconds; } return minutes + ":" + seconds; }, play() { this.playing = true; }, pause() { this.playing = false; }, togglePlay() { this.playing = !this.playing; }, connectedCallback(element) { this.listenTo("playing", function(event, isPlaying) { if (isPlaying) { element.querySelector("video").play(); } else { element.querySelector("video").pause(); } }); this.listenTo("currentTime", function(event, currentTime) { //👀 const videoElement = element.querySelector("video"); //👀 if (currentTime !== videoElement.currentTime) { //👀 videoElement.currentTime = currentTime; //👀 } //👀 }); //👀 } } }); 

Result

When finished, you should see something like the following JS Bin:


Tag cloud