Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

155
Views
Setting video on pause when invisible

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

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],
};
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!