1

My question is based on this one:

Event listener for when element becomes visible?

I want a video element to start playing automatically when became visible and to stop when became invisible. The element is a slide in a carousel component (namely, owl-carousel, though I think it doesn't matter). So I did the following:

  • Marked the video element with autovideo class.
  • Included the respondToVisibility function code from the answer.
  • Attached a stub event handler.

So now the code looks like this:

function respondToVisibility(element, callback) {
  var options = {
    root: document.documentElement,
  };

  var observer = new IntersectionObserver((entries, observer) => {
    entries.forEach(entry => {
      callback(entry.intersectionRatio > 0);
    });
  }, options);

  observer.observe(element);
}

// Autoplay video when visible.
$('.autovideo').each(function ()
{
    respondToVisibility(this, function (isVisible)
    {
        alert('isVisible: ' + isVisible);
    });
});

It works as intended, when I click the carousel buttons Next/Prev (display:none style is being added/removed under the hood). But when I scroll the page down and the video element is out of screen, the event is not fired.

I guessed that Intersection Observer API means intersection of an element with the visible part of the browser window (viewport). Should I use an additional observer for scrolling the video out of the window or change the current one?

Shtole
  • 77
  • 6
  • Can you use the owl.carousel.changed event, or similar? See https://stackoverflow.com/questions/55443137/trigger-event-on-slide-change – James May 26 '22 at 14:33
  • Hi @James, owl.carousel.changed event is fired only when you click Next/Prev or swipe the slides. It's fine, but I want a universal event handler for both hiding via 'display:none' and scrolling down. Intersection Observer API seemed the right solution to me, but I can't get what's wrong with the callback implementation. – Shtole May 26 '22 at 17:17

1 Answers1

0

According to documentation (https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API#intersection_observer_concepts_and_usage):

To watch for intersection relative to the device's viewport, specify null for root option.

As I did so, the callback is called now as well when I scroll the page down.

Also, I guess the entry.intersectionRatio > 0 condition isn't very good in my case, the video should be visible for more than 50%.

var options =
{
    root: null,
    threshold: [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1],
};
Shtole
  • 77
  • 6