Skip to content
Advertisement

intersection observer works only for the first video

I need to pause a video if it is not in view
the below code works only for the first video in list
how to make it working for all .bvideo ?

<video class='bvideo' src='a.mp4' poster='a.jpg' preload='none' controls></video>
<video class='bvideo' src='b.mp4' poster='b.jpg' preload='none' controls></video>
<video class='bvideo' src='c.mp4' poster='c.jpg' preload='none' controls></video>

let io = new IntersectionObserver((entries) => {
  entries.forEach(entry => {
    if(!entry.isIntersecting){entry.target.pause();}
  });
});

$(document).ready(function(){
    io.observe(document.querySelector('.bvideo'));
});

Advertisement

Answer

Use querySelectorAll() method.

$(document).ready(function() {
    let bvideos = document.querySelectorAll('.bvideo');
    bvideos.forEach(bvideo => io.observe(bvideo));
});
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement