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?