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:
autovideo class.respondToVisibility function code from the answer.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?
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
nullforrootoption.
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],
};