Home > Back-end >  shorter way to pause a video if it is fully out of view
shorter way to pause a video if it is fully out of view

Time:02-13

I have this code to pause a video if it is fully out of view
it works, but I want to make it shorter
for example, to avoid forEach loop, because this is the only video on page
also - maybe to avoid a separate modify function - but place el.pause() inside the first block of js code
I tried on various ways and getting various errors in console
pls help

<video id='vsingle' src='lorem.mp4' poster='lorem.jpg' controls></video>   

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

function modify(el){el.pause();}

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

CodePudding user response:

You could simplify this code a little by removing the modify function:

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