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);

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

querySelector("video");
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 Design, a digital agency that builds WordPress websites. I read, write and design constantly!
We're looking for new authors. Explore Isotropic Jobs.
Close
🇺🇸 English
Save posts, access exclusive content, join members-only communities and more.
Dark Mode Toggle
linkedin facebook pinterest youtube rss twitter instagram facebook-blank rss-blank linkedin-blank pinterest youtube twitter instagram