JS/CSS — Transition effect for looping background video

Liu Ting Chun
2 min readFeb 26, 2022

Using videos as the background is a common practice nowadays for creative web design. However, most videos are not self-looped. There is a flicking of frames when those videos are repeated, which is simply — ugly.

Repeating a video that is not self-looped.

This issue can be solved by simply adding a transition effect at the end of the video, and it is extremely easy to do that. We don’t need any video editing software. The solution needs only JS and CSS. Besides, it is universal. That single function will work for all videos. Fine-tuning is not required.

Video with transition effect

The Code

Let’s keep it short for simplicity. To begin with, instead of letting the video play and repeat itself, we need to write a function to manage the loop mechanism such that we can add and remove a CSS class in between.

function playVideo(e) {
e.play();
e.classList.remove('fading');
setTimeout(() => {
e.classList.add('fading');
}, (e.duration / e.playbackRate - 1) * 1000)
}

We calculate the video length and add the fading CSS class 1 second (you can change this value if you want a longer transition) before the end of the video.

--

--

Liu Ting Chun

Web developer from Hong Kong. Most interested in Angular and Vue. Currently working on a Nuxt.js + NestJS project.