isotropic-2022
Share
Blog
Search
Menu

Autoplay Videos When In Viewport

By James LePage
 on May 21, 2021
Last modified on January 6th, 2022

Autoplay Videos When In Viewport

By James LePage
 on May 21, 2021
Last modified on January 6th, 2022

In this article, we're going to discuss how to use IntersectionObserver to make video clips play only when in the viewport (then stop as the visitor continues to scroll).

This is a perfect solution for long video clips that you want to make sure the visitor watches (get the benifits of autoplay, but ensure that the video is only playing when in viewport so the visitor doesn't miss out on anything important).

How will we do this with pure Javascript? Easy... IntersectionObserver.

This API can be used in many ways, but we're going to focus on the video-specific implementation.

A common use case would be an advertisement with autoplay enabled (plays as soon as it loads), and then stops when out of viewport. This ensures all visitors see the ad.

const video = document.querySelector("video");
let playState = null;

const observer = new IntersectionObserver((entries) => {
  entries.forEach((entry) => {
    if (!entry.isIntersecting) {
      video.pause();
      playState = false;
    } else {
      video.play();
      playState = true;
    }
  });
}, {});

observer.observe(video);

const onVisibilityChange = () => {
  if (document.hidden || !playState) {
    video.pause();
  } else {
    video.play();
  }
};

document.addEventListener("visibilitychange", onVisibilityChange);Code language: JavaScript (javascript)

What do you need to do? Nothing but change the following line, to be more specific:

querySelector("video");Code language: JavaScript (javascript)
Subscribe & Share
If you liked this content, subscribe for our monthly roundup of WordPress news, website inspiration, exclusive deals and interesting articles.
Unsubscribe at any time. We do not spam and will never sell or share your email.
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
Article By
James LePage
Contributors/Editors
notloggedin
James LePage is the founder of Isotropic, a WordPress education company and digital agency. He is also the founder of CodeWP.ai, a venture backed startup bringing AI to WordPress creators.
We're looking for new authors. Explore Isotropic Jobs.
linkedin facebook pinterest youtube rss twitter instagram facebook-blank rss-blank linkedin-blank pinterest youtube twitter instagram