0

I found an interesting tutorial on how to use IntersectionObserver to play/pause videos as the are scrolled into view, however I couldn't get it to work on a page with multiple videos.

I then found this post: HTML5 and Javascript to play videos only when visible

But the only answer from that which works is the following, and I can't get it to work on mobile browsers:

function playVisibleVideos() {
  document.querySelectorAll("video").forEach(video => elementIsVisible(video) ? video.play() : video.pause());
}

function elementIsVisible(el) {
  let rect = el.getBoundingClientRect();
  return (rect.bottom >= 200 && rect.right >= 0 && rect.top <= 500 && rect.left <= (window.innerWidth || document.documentElement.clientWidth));
}

let playVisibleVideosTimeout;
window.addEventListener("scroll", () => {
  clearTimeout(playVisibleVideosTimeout);
  playVisibleVideosTimeout = setTimeout(playVisibleVideos, 100);
});

window.addEventListener("resize", playVisibleVideos);
window.addEventListener("DOMContentLoaded", playVisibleVideos);

Any help?

  • Shouldnt be `rect.bottom <= 500` and `rect.top >= 200` – ariel Apr 03 '20 at 05:09
  • I don't think it matters does it? That just sets how much of the video frame has to be visible to start/stop. The problem right now is it doesn't work at all on mobile browsers. The above code (with or w/o swapping the numbers) seems to work fine on my laptop. –  Apr 03 '20 at 05:13
  • It’s seeming like this is only a problem on Chrome mobile browsers maybe. –  Apr 03 '20 at 05:46
  • @epignosis567 , you said: *"...I can't get it to work on mobile browsers"* What mobile browsers are you having trouble on? What actual devices are you using? *Not working* is too vague...so ***specifically how does your code not work?*** Moreover, CSS plays an important part when you expect the same behavior in mobile as you would on desktop. Also, I believe you want to scroll horizontally? If so...what measures have you taken to ensure that when in mobile that the page locks orientation to landscape? – zer00ne Apr 04 '20 at 10:31

0 Answers0