JS/CSS — Transition effect for looping background video
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.
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.
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.