views:

190

answers:

1

I know how to get the scrollTop of a page, I use this simple JS function (code copied around):

function GetScrolledTop() 
{
   //I never work in IE quirkmode, I always use DOCTYPE as 1st line, so I don't need to test for document.body.scrollTop
   return self['pageYOffset'] || document.documentElement.scrollTop; 
}

This works and my problem is the following: I tried to add it in the page onload event

<body onload="alert(GetScrolledTop());">

On page load I get ZERO (which make sense), but the problem is that I get ZERO even if I scroll the page and then reload it without touching the scrollbar.

It seems like the browser does:

  1. loads page
  2. calls my GetScrolledTop() (so obviously shows ZERO)
  3. then scrolls the page to where it was before.

Do you know how to get the scolledTop after the step 3? I mean how to get the scrolledTop AFTER the browser scrolled the page? (maybe without using a timer)

Thanks!

+2  A: 

Probably not without using a timer. But you might be able to use a timer with a 0ms delay, which would execute the function when the thread becomes idle, whilst still appearing to be instant:

<body onload="window.setTimeout(function () { alert(GetScrolledTop()); } , 0);">

EDIT - Thought it might also be worth mentioning that most browsers support the onscroll event, which should fire after the window scrolls.

Andy E
+1 the window.setTimeout trick works in all browser except IE7 and IE8 (didn't try IE6). Using the onscroll event works everywhere.
Marco Demajo