Sean Bone
Sean Bone

Reputation: 3546

Detecting by how much user has scrolled

I have an image pop-up ability on my website, in order to show users the full resolution picture when they click on a smaller version on the page.

This is the current CSS that positions it:

div#enlargedImgWrapper {
    position: absolute;
    top: 30px;
    left: 55px;
    z-index: 999;
}

The problem now is that if I click on an image further down the page, the window still appears in the top left corner of the page, where I can't see it until I scroll back up. I need it to appear relative to the window, whatever its current position relative to the document is.

Note: I don't want to use position: fixed; as some images might be taller than the screen, so I want users to be able to scroll along the image as well.

My idea was to use JS to change the top value:

var scrollValue = ???;
document.getElementById('enlargedImgWrapper').style.top = scrollValue+30 + 'px';

How can I detect by how much the user has scrolled down the page (var scrollValue)?
Or is there a 'better' way to do this?

Edit: if possible I would like to do this without jQuery.

Upvotes: 46

Views: 69369

Answers (3)

Eugene
Eugene

Reputation: 1142

In 2024 use scrollY and scrollX. As pageYOffset and pageXOffset are depriciated. Browser support: caniuse.com

const scrollTop = window.scrollY;
const scrollLeft = window.scrollX;

So it will be:

document.getElementById('enlargedImgWrapper').style.top = window.scrollY + 30 + 'px';

Upvotes: 3

Rab
Rab

Reputation: 35572

document.getElementById('enlargedImgWrapper').scrollTop;

MDN

This property's value equals the current vertical offset of the content within the scrollable range. Although you can set this property to any value, if you assign a value less than 0, the property is set to 0. If you assign a value greater than the maximum value, the property is set to the maximum value.

You can set this property inline, but the results might be inconsistent while the document is loading.

scrollTop property

Upvotes: 6

Engineer
Engineer

Reputation: 48793

Pure JavaScript uses scrollTop and scrollLeft:

var scrollLeft = (window.pageXOffset !== undefined) ? window.pageXOffset : (document.documentElement || document.body.parentNode || document.body).scrollLeft;
var scrollTop = (window.pageYOffset !== undefined) ? window.pageYOffset : (document.documentElement || document.body.parentNode || document.body).scrollTop;

https://developer.mozilla.org/en-US/docs/Web/API/Element.scrollTop

jQuery version:

var scrollLeft = $(window).scrollLeft() ;
var scrollTop = $(window).scrollTop() ;

What you need is this:

document.getElementById('enlargedImgWrapper').style.top = (scrollTop+30) + 'px';

Upvotes: 83

Related Questions