jonny bordo jonny bordo - 3 months ago 26
AngularJS Question

jQuery scrollTop() returns 0 for all elements

At my job we have a one page site I created with AngularJS.

We're using the ui-router plugin (version 0.2.0).

Recently I've noticed that when moving from one state to another, the window isn't scrolled to the top.

I even tried to scroll it to the top manually using jQuery's

scrollTop()
function on every state change (using the
$stateChangeSuccess
event). But it didn't work.

So I started investigating, and I've noticed that
scrollTop()
is returning 0 for every element on the page.

Not only that, but when I print the
window.scrollY
to the console I get 0 (no matter where I'm at on the page). Not only in my code, but even if I just write it in the chrome dev tools console.

I've written several apps with AngularJS and ui-router, and it only happens in this particular one.

I've checked to see if I have overwritten the
scrollTop()
function or even the
window.scrollY
field, but haven't found anything.

I've tried using the
ui-view
with
autoscroll="true"
and
autoscroll="false"
, but it didn't make a difference.

I also tried giving the
html
and the
body
elements
height:100%
, and I also tried it without. But nothing.

I really don't know what to do next.

I wasn't able to reproduce the problem, but if you think there is any code I should post here that could be of any help, I'll be glad to do that.

Thanks!

EDIT:

I've run this function on the console:

var l = $('*').length;
for(var i = 0; i < l; i++) {
var elem = $('*:eq(' + i + ')');
if(elem.scrollTop() > 0) {
console.log(elem, elem.scrollTop());
}
}


The function printed out only one element with it's top scroll.

The element is a wrapping div that holds the whole content and the main view (I have nested views in my app).

If I use
scrollTop(0)
on this element I get what I wanted, but it only deals with the symptom, and not the real problem.

Answer

As @Hans commented, there wasn't actually a problem. I had a wrapping element, that was positioned absolute with:

top:0;
bottom:0;
left:0;
right:0;
overflow:auto

So The window's scrollTop was always 0, and the scrollbar actually belonged to the wrapping element.

Since I could't get rid of the wrapping element's positioning, I used ui-router's $stateChangeSuccess event, and manually scrolled the wrapping element to the top.