In this lesson I create a custom video player.
First I grab all of the required elements and put them into variables. I listen for the following events:
-
<video>
- 'click', togglePlay()
- 'play', updateButton()
- 'pause', updateButton()
- 'timeupdate', handleProgress()
-
.toggle
-
[data-skip]
-
.player__slider
- 'change', handleRangeUpdate()
- 'mousemove', handleRangeUpdate()
-
.progress
- 'click', scrub(e). Here I scrub the video to the clicked event location.
- 'mousemove', (e) => mousedown && scrub(e). Here I'm making sure to only scrub the video while the mouse is down and moving.
- 'mousedown', () => mousedown = true
- 'mouseup', () => mousedown = false
Functions
-
togglePlay()
- If the video is paused, set the video to playing, if the video is playing, set the video to paused.
-
updateButton()
- If the video is paused, set the text to '►', if the video is playing, set the text to '❚❚'.
-
skip()
- Calculate a new 'currentTime' on the video using the value from the [data-skip] attribute.
-
handleRangeUpdate()
- Handle updated slider input values. Set the video[this.name] value to this.value. For example, set the volume to the new value on the volume slider.
-
handleProgress()
- Calculate the 'percent' remaining ((video.currentTime / video.duration) *100). Then update the width of the 'progressBar' to match the 'percent' by injecting 'percent' into the style attribute (progressBar.style.flexBasis = `${percent}%`).
-
scrub(e)
- figure out the 'scrubTime' ((e.offsetX / progress.offsetWidth) * video.duration). Then set the video time to the 'scrubTime'.
See the Pen
JavaScript30 - 11 - Custom Video Player by Corey Noble (@CoreyNoble)
on CodePen.