Driving a gradient progress bar from video playback

A workplace training video provided the unexpected demo subject: its progress bar grew from green to blue as playback advanced. Gradient-filled <progress> elements are already achievable — Pankaj Parashar covered that in a 2016 CSS-Tricks post — but the interesting half of the problem is feeding the bar a live percentage from a <video> element, which takes a little JavaScript arithmetic.

The markup

<figure>
  <video id="video" src="http://html5videoformatconverter.com/data/images/happyfit2.mp4"></video>
  <figcaption>
    <button id="play" aria-label="Play" role="button">►</button>
    <progress id="progress" max="100" value="0">Progress</progress>
    </figcaption>
</figure>

The central element is the progress bar itself:

<progress id="progress" max="100" value="0">Progress</progress>

max is set to 100 and value starts at 0, so the progress can be read as a percentage from start to finish.

Painting the gradient

Styling details are left to the linked article; the essentials are the vendor-prefixed pseudo-elements needed to fill the bar. WebKit and Mozilla browsers each handle progress elements in their own way, so the CSS ends up rather verbose:

/* Fallback stuff */
progress[value] {
  appearance: none; /* Needed for Safari */
  border: none; /* Needed for Firefox */
  color: #e52e71; /* Fallback to a solid color */
}

/* WebKit styles */
progress[value]::-webkit-progress-value {
  background-image: linear-gradient(
    to right,
    #ff8a00, #e52e71
  );
  transition: width 1s linear;
}

/* Firefox styles */
progress[value]::-moz-progress-bar {
  background-image: -moz-linear-gradient(
    right,
    #ff8a00, #e52e71
  );
}

Computing the value from the video

The math breaks into three steps:

  • Read the current time of the video.
  • Read the duration, to express that time as a fraction of the whole.
  • Calculate the progress using part / whole = % / 100, which in video terms is currentTime / duration = progress value.

With the elements and video properties selected:

// Variables
const progress = document.getElementById( "progress" );

// Properties
// progress.value = The calculated progress value as a percent of 100
// video.currentTime = The current time of the video in seconds
// video.duration = The length of the video in seconds

…the value can be computed and written to the bar:

function progressLoop() {
  setInterval(function () {
    document.getElementById("progress").value = Math.round(
      (video.currentTime / video.duration) * 100
    );
  });
}

The division returns a decimal, so Math.round() rounds it to the nearest integer. At this point the gradient bar animates as the video plays.

Displaying elapsed time

A timer next to the bar is a small bonus, since the needed data is already available. A <label> works well here because <progress> can be associated with one:

<figure>
  <video controls id="video" src="http://html5videoformatconverter.com/data/images/happyfit2.mp4"></video>
  <figcaption>
    <label id="timer" for="progress" role="timer"></label>
    <progress id="progress" max="100" value="0">Progress</progress>
    </figcaption>
</figure>

Assign the label to a variable and print the current time into it with innerHTML:

const progress = document.getElementById("progress");
const timer = document.getElementById( "timer" );

function progressLoop() {
  setInterval(function () {
    progress.value = Math.round((video.currentTime / video.duration) * 100);
    timer.innerHTML = Math.round(video.currentTime) + " seconds";
  });
}

progressLoop();

Formatting that value as HH:MM:SS is left as further work.

Replacing the native controls

Omitting the controls attribute on <video> removes the built-in play, seek and volume UI, which otherwise duplicates the custom progress bar. That means supplying at least a play/pause control — a plain <button> in the markup:

<figure>
  <video id="video" src="http://html5videoformatconverter.com/data/images/happyfit2.mp4"></video>
  <figcaption>
    <label id="timer" for="progress" role="timer"></label>
    <button id="play" aria-label="Play" role="button">►</button>
    <progress id="progress" max="100" value="0">Progress</progress>
    </figcaption>
</figure>

…wired to a function that toggles playback on click:

button = document.getElementById( "play" );

function playPause() { 
  if ( video.paused ) {
    video.play();
    button.innerHTML = "❙❙";
  }
  else  {
    video.pause(); 
    button.innerHTML = "►";
  }
}

button.addEventListener( "click", playPause );
video.addEventListener("play", progressLoop);

Dropping the native controls wouldn't be the choice for a real project, but it keeps this experiment self-contained.

Tidying the code: explicit states and requestAnimationFrame

Neal Fennimore reviewed the code and suggested changes that make it more legible and, more importantly, give the player well-defined states:

// States
const PAUSED = 'paused';
const PLAYING = 'playing';

// Initial state
let state = PAUSED;

State is checked before the progress function is invoked, and the play, pause and click events drive the logic:

// Animation loop
function progressLoop() {
  if(state === PLAYING) {
    progress.value = Math.round( ( video.currentTime / video.duration ) * 100 );
    timer.innerHTML = Math.round( video.currentTime ) + ' seconds';
    requestAnimationFrame(progressLoop);
  }
}

video.addEventListener('play', onPlay);
video.addEventListener('pause', onPause);
button.addEventListener('click', onClick);

The same snippet also swaps setInterval for requestAnimationFrame, improving animation performance.