Home:ALL Converter>scrollto only works if scroll position is top of page

scrollto only works if scroll position is top of page

Ask Time:2021-09-22T05:21:39         Author:Bruce

Json Formatter

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?

Author:Bruce,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/69275687/scrollto-only-works-if-scroll-position-is-top-of-page