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

145
Views
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 answers
Answer question

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 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!