Daniel
Daniel

Reputation: 81

How to find the scroll position of a particular element?

This might seem like a basic question but for some reason things like document.body.offsetTop, window.scrollY, window.scrollTop, document.body.scrollTop, window.pageYOffset, and the like are returning 0 or undefined regardless of where I've scrolled on the page. A couple other details, this is on mobile Safari which I'm running on the XCode simulator and inspecting with the Safari developer tool. My code, which uses document.pageYOffset, works properly on desktop browsers. The only other limitation is that I can't use jQuery. All the other times this question has been asked, the answer uses things like window.scrollY or something like that which just don't work here. Are there alternate ways to get a page's (or a particular element's) scroll position? (Edit: relative to the viewport)

Upvotes: 1

Views: 5121

Answers (2)

Daniel
Daniel

Reputation: 81

It turns out that selecting the element and then calling getBoundingClientRect works for this. So for example: let containerPosition = document.getElementById('select-unauthenticated-home-container').getBoundingClientRect().top; And then you can add your behavior based on that value.

Upvotes: 2

Saleh Mosleh
Saleh Mosleh

Reputation: 544

Try to use jquery , $("selector").scrollTop and $("selector").scrollLeft .

var scrolltop = $("selector").scrollTop();
var scrollleft = $("selector").scrollLeft();

Upvotes: 0

Related Questions