Home > Blockchain >  scrollto only works if scroll position is top of page
scrollto only works if scroll position is top of page

Time:09-22

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?

CodePudding user response:

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?

  • Related