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

142
Visualizações
scrollto only works if scroll position is top of page

I have dozens of videos on a page.

When the video is played, I change several attributes (background dark, increase size of video, align to center video, scroll to top of video so it is only element shown, etc).

My script looks like the following:

document.querySelectorAll('div div video').forEach(function(e) {
  e.addEventListener('playing', function(event) {
    e.style.width = '';
    e.style.height = '95vh';
    e.closest('div').style.textAlign = 'center';
    e.closest('div').style.width = '100%';
    e.previousElementSibling.style.color = '#ccc';
    var pos = e.getBoundingClientRect();
    window.scrollTo(0,pos.top - 40);
    b = document.querySelector('body');
    b.style.backgroundColor = '#101010';
  });
});

The problem is

var pos = e.getBoundingClientRect();
window.scrollTo(0,pos.top - 40);

the above code only seems to work if the scroll is at the top of the page. If one has scrolled down the page before clicking play, the scroll position ends up being in the wrong place.

I created an example at https://jsfiddle.net/017mxvbs/ To see what I mean load fiddle, click play on a video without scrolling. Refresh page, scroll down and click play on one of the last videos.

So what am I doing wrong?

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

0

Use offsetTop instead.

document.querySelectorAll('div  div video').forEach(function(e) {
  e.addEventListener('playing', function(event) {
    e.style.width = '';
    e.style.height = '95vh';
    e.closest('div').style.textAlign = 'center';
    e.closest('div').style.width = '100%';
    e.previousElementSibling.style.color = '#ccc';
    window.scrollTo(0,e.offsetTop);
    b = document.querySelector('body');
    b.style.backgroundColor = '#101010';
  });
});

More information on the difference between getBoundingClientRect and offsetTop here: Difference between getBoundingClientRect().top and offsetTop?

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