Categories
JavaScript Answers

How to make a HTML5 video loop seamlessly with JavaScript?

Spread the love

Sometimes, we want to make a HTML5 video loop seamlessly with JavaScript.

In this article, we’ll look at how to make a HTML5 video loop seamlessly with JavaScript.

How to make a HTML5 video loop seamlessly with JavaScript?

To make a HTML5 video loop seamlessly with JavaScript, we can watch when the video almost ends and then set its time back to the start time.

For instance, we write:

<video width="300" height="300" controls loop autoplay preload="true">
  <source src="https://file-examples-com.github.io/uploads/2017/04/file_example_MP4_480_1_5MG.mp4" type="video/mp4">
</video>

to add a video element.

Then we write:

const vid = document.querySelector("video");
vid.addEventListener("timeupdate", (e) => {
  if (e.target.currentTime >= 29) {
    e.target.currentTime = 0.0;
  }
});

We select the video with querySelector.

Then we call addEventListener with 'timeupdate' to listen for the timeupdate event.

If the currentTime of the video is close to the end, then we set the currentTime back to 0 to restart the video.

Conclusion

To make a HTML5 video loop seamlessly with JavaScript, we can watch when the video almost ends and then set its time back to the start time.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *