Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

88
Visualizações
Intersection observer for multiple videos on the same page

I have a portfolio page made in WordPress and on the page I have 5 videos that need to be played when in viewport and stopped when out of viewport.

I have used the following script that works only on the first video on the page.

const video = document.querySelector("video");
let playState = null;
const observer = new IntersectionObserver((entries) => {
  entries.forEach((entry) => {
    if (!entry.isIntersecting) {
      video.pause();
      playState = false;
    } else {
      video.play();
      playState = true;
    }
  });
}, {});
observer.observe(video);
const onVisibilityChange = () => {
  if (document.hidden || !playState) {
    video.pause();
  } else {
    video.play();
  }
};
document.addEventListener("visibilitychange", onVisibilityChange);
querySelector("video");

And here is the link to the page: http://wemedia.co.rs/portfolio-2/

So what I want to achieve is to play and pause every video when in or out of viewport.

Thank you.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You are only selecting one video to use throughout your whole js script.

You need to remember that video represents only a single video and if you want to control multiple, you need to reference them in every function that you call.

I also don't see a purpose in using playState since the way you have it, it is basically an indicator of whether the first video is on screen or not.

const videos = document.querySelectorAll("video"); // Select ALL the Videos
const observer = new IntersectionObserver((entries) => {
  entries.forEach((entry) => {
    if (!entry.isIntersecting) {
      entry.target.pause(); // Pause the TARGET video
    } else {
      entry.target.play(); // Play the TARGET video
    }
  });
}, {});
for (const video of videos) observer.observe(video); // Observe EACH video
const onVisibilityChange = () => {
  if (document.hidden) {
    for (const video of videos) video.pause(); // Pause EACH video
  } else {
    for (const video of videos) video.play(); // Play EACH video
  }
};
document.addEventListener("visibilitychange", onVisibilityChange);
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda