user12051965
user12051965

Reputation: 147

JavaScript avoid reset to top of page after position:fixed

I have scroll pagination to my app where I display some images. When I click an image, a modal opens up displaying the image full screen. In order to prevent scroll in the body I provide the following class to html, body tags. Problem is that if I scroll down by 40 images select an image and after I close that modal, the images feed starts displaying again from the top of the page. I want to avoid this an continue from the position that I was before clicking that image.

.item-mdl-plh {
    overflow: hidden !important;
    position: fixed;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
}

I have found similar questions to mine here, and implemented this one but it does not work,scrollTop always returns 0 from the feed div element.

How do I prevent custom full screen from resetting the scroll position?

And others in jQuery but did not understand:

Avoid reverting to top of page when setting <body> position to fixed with jQuery

I would like to understand how can I achieve this behavior that I want using vanilla JavaScript.

Upvotes: 1

Views: 706

Answers (1)

a.mola
a.mola

Reputation: 4011

If you've decided to use the scrollTop method, You can use this.

I don't know why, but scrollTop always returns 0 in chrome. But the pageYOffset returns the intended value.

So you can use something like this.

let scrollTop = 0;

function open_modal() {
    scrollTop = pageYOffset || document.documentElement.scrollTop || 0;
    // Modal
}

function close_modal() {
    // Remove modal
    scrollTo(0, scrollTop); // After removing fixed position from body, scroll back to last recorded posititon
}

Upvotes: 1

Related Questions