This is the 28th project of Wes Bos's JS30 series. To see the whole 30 part series, click here Today we'll build an experimental video speed controller UI.
Video -
Starter code -
We'll be building a video speed controller where the user can control the video speed just by hovering the mouse over the controller bar. This will be a mixture of various things we've dealt before!
The HTML we have
<div class="wrapper">
<video class="flex" width="765" height="430" src="http://clips.vorwaerts-gmbh.de/VfE_html5.mp4" loop controls></video>
<p>
<div class="speed">
<div class="speed-bar">1×</div>
</div>
</div>
video.flex
is the video element whose playback rate we'll change, the div.speed
element is the speed controller and div.speed-bar
is the current playback speed indicator.
Let's select all the DOM elements we'll use
const speed = document.querySelector('.speed');
const bar = speed.querySelector('.speed-bar');
const video = document.querySelector('video');
//min, max playback speed
const min = 0.4;
const max = 4;
Listen to mouse move on the speed controller
speed.addEventListener('mousemove', handleMove)
The handleMove
function does two things - changes the height of div.speed-bar
and changes the playback rate of the video.
function handleMove(e) {
const y = e.pageY - this.offsetTop
const percent = y / this.offsetHeight
const height = Math.round(percent * 100) + '%'
bar.style.height = height
}
y = e.pageY - this.offsetTop
percent = y / this.offsetHeight
height = Math.round(percent * 100) + '%'
speed-bar
to that height. bar.style.height = height
// in handleMove()
const playbackRate = percent * (max - min) + min;
bar.textContent = playbackRate.toFixed(2) + '×';
video.playbackRate = playbackRate;
To get the playback rate we map the percentage
into the min
to max
range, and add the min offset. That is how we get playbackRate = percent * (max - min) + min
.
We then just update the text in the speed bar and the playback rate of the video.
This completes our exercise. The final codepen is below -