Autoplay Videos When In Viewport

Published: 4 months ago

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");
Join Our Newsletter
Here's what you get: A once a week newsletter that contains original content, aggregated posts, WordPress deals, and anything else we think you'd like. We don't spam or sell your email address. Unsub at any time.
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
IsoGroup- Web Dev/Design, WordPress and More

Affiliate Disclosure: Some links on this website are affiliate links. We make commissions for purchases made through those links.

We only recommend items/tools that we've personally used and like.

Full Disclosure | FTC Statement

Join Our Newsletter
Over 4,000 Design Lovers and Problem Solvers.

Author

A relationship driven website creation company.

Connect

© ISOTROPIC, LLC 2016-2021
linkedin facebook pinterest youtube rss twitter instagram facebook-blank rss-blank linkedin-blank pinterest youtube twitter instagram