Rick Strahl's Weblog  

Wind, waves, code and everything in between...
.NET • C# • Markdown • WPF • All Things Web
Contact   •   Articles   •   Products   •   Support   •   Advertise
Sponsored by:
West Wind WebSurge - Rest Client and Http Load Testing for Windows

Retrieving Browser Scroll Position in JavaScript


:P
On this page:

Man what a pain in the ass this is.  I'm still working out some additional details that were pointed out to me with the wwHoverPanel control. The main problem is that reliably getting the scroll position is very fickle.

 

Originally I had tried to rely on document.body.scrollTop which works fine for the original demos I created, but it fails when running in a MasterPage. I don't think it's the master page per se that is making this different, but probably the containership inside of the body tag.

 

In any case in the more complex page document.body.scrollTop returns false and this is were things diverge in browsers with IE requiring the use of the parentElement (HTML) and FireFox using pageYOffset which is a non-standard tag (so much for FireFox always following standards).

 

The code that actually seems to work in the scenarios I tried is this:

 

var ScrollTop = document.body.scrollTop;

 

if (ScrollTop == 0)

{

    if (window.pageYOffset)

        ScrollTop = window.pageYOffset;

    else

        ScrollTop = (document.body.parentElement) ? document.body.parentElement.scrollTop : 0;

}

 

So let's see here, we have scrollTop on different containers and we have pageYOffset neither of which seems particularily clear description of the task. The window should have a scroll position because that's really what we're after in this case…

 

I hate browser scripting… <g>

 

(and yes I know what you're going to say Bertrand – "that's why we're doing it for you…" <g>).

 

Thanks for Chris and Mike McDonald for all their comments on some of this stuff. If you want to follow this discussion related to wwHoverPanel movement closer you can click here and here.

 


The Voices of Reason


 

Bertrand Le Roy
February 24, 2006

# re: Retrieving Browser Scroll Position in JavaScript

Actually, that's not what I was going to say. I was going to say that you should feel free to have a peek at the ASP.NET resource script that's doing that and take some "inspiration" from it. For all I know, it may even be possible to call the script directly and have it do the right thing (pure speculation alert).

Elvis Tam
August 30, 2006

# re: Retrieving Browser Scroll Position in JavaScript

Hey there! Thanks so much for this code! I was finding the same behavior in my browsers when trying to implement my scroll position memory function. ON my test page it worked fine, but when I went to my application, it didn't.

I found out why , so this might be of interest to you. I finally zeroed the issue down to the doc type!

If you use a doctype on your page , for some reason it returns 0 for scrolltop property. My test page didn't have one since I just used the bare minimum code so it worked but my application pages use doctypes. Try it out, take it out, I would be curious if that was the problem for you.

Anyhow thanks for this solution again!

# DotNetSlackers: Retrieving Browser Scroll Position in JavaScript


leandro koiti
June 04, 2007

# re: Retrieving Browser Scroll Position in JavaScript

u always saves my life, thanks a lot!

CSJ
July 17, 2007

# re: Retrieving Browser Scroll Position in JavaScript

Thank you! That was about driving me crazy.

mars
July 27, 2007

# re: Retrieving Browser Scroll Position in JavaScript

Thank you so much for your coherent solution to a problem in the incoherent mess that is browser technology.

If you add up all the time lost to deciphering this incoherent mess I think it would be safe to declare the current state of browser technology a national (or international) disaster.

Ali
August 26, 2007

# re: Retrieving Browser Scroll Position in JavaScript

Thanx Man ... It helped me a lot ... I had a context menu on tree nodes but it appeared in wrong place.I could maintain the position this way.
thank again

Nishigandha
October 20, 2007

# re: Retrieving Browser Scroll Position in JavaScript

COOL boss thanks a lot..
it solved my problem with context menu..
for MS Virtual Earth

when i deployed my webpart into sharepoiint site...
the menu was needed to adjust when scroll postion is graeter than 0;

Shameer
March 12, 2008

# Mr

Thanks a lot dude, for this piece of code. It is really valuable when we really need it. And I got it in a really needy time.

henderson
April 24, 2008

# re: Retrieving Browser Scroll Position in JavaScript

Thanx a lot dude, it just sorted out one of big bug of one of my drag and drop with scrolling problem. And your blog is also excellent. Thanx again.

# Improved Search Engine Placement

It\'s been really long since I started reading your posts and today I just want to say that your blog is great!

Stefan Lisper
October 27, 2008

# re: Retrieving Browser Scroll Position in JavaScript

Cheers! Thank god for people like you!

kunal
March 24, 2009

# re: Retrieving Browser Scroll Position in JavaScript

just wonderful.. thanks!!!!

Aaron
May 15, 2009

# re: Retrieving Browser Scroll Position in JavaScript

Doctype = strict mode in IE.
I've had some success with:

document.documentElement.scrollTop;


It's a major pain, but it worked as far as IE 6.0
I have not had the chance to test this method in IE 7 or IE 8. This creates a problem, as I'm in the middle of redesigning my website pretty much from the ground up...
I figure IE7 and IE8 are going to cause me MAJOR headaches...

Thanks for the snippet though. This is getting bookmarked as of right now.

Hilliard Johnson
July 07, 2009

# re: Retrieving Browser Scroll Position in JavaScript

Dude (that's how we roll in California <g>) -

This wasn't exactly a timesaver, since figuring out which window/document you have to address in a multi-layered 'thang' with frames and an iFrame is no simple task - it WAS however a LIFESAVER in terms of being able to dig it out at all...

May I suggest here that the new IE8 script debugger is really helpful in figuring out which layer you are addressing, and also setting breakpoints to see which variables are actually being used... in my case, I have an industrial app which I don't paticularly care works over the general internet...

Thanks for posting this tip - it's the only one on the subject worth noting that I have found... and what a MESS is the DOM!!!

- h.

wunderleyg
July 14, 2009

# re: Retrieving Browser Scroll Position in JavaScript

Thanks for the code for this. I had a popup windoiw that kept kicking me to the top of the page when it was displayed. Your code to get the scroll position really helped me out.

Chris
September 08, 2009

# re: Retrieving Browser Scroll Position in JavaScript

Add a DOCTYPE to keep up with the standards and watch your code break. Yippee. Thanks very much for this fix! Amazing to think this is still helping people out over 3 years later!

SunHateR
October 03, 2009

# re: Retrieving Browser Scroll Position in JavaScript

Thanks plain example. I changed your code using one expression:
var top = document.body.scrollTop
    ? document.body.scrollTop
    : (window.pageYOffset
        ? window.pageYOffset
        : (document.body.parentElement
            ? document.body.parentElement.scrollTop
            : 0
        )
    );

Milang
February 24, 2010

# re: Retrieving Browser Scroll Position in JavaScript

Hey, thanks man, this actually works!
You saved my life (ass)! :)

Raj Ahuja
March 10, 2010

# re: Retrieving Browser Scroll Position in JavaScript

Thanks it is very helpful for me.

dima
March 18, 2010

# re: Retrieving Browser Scroll Position in JavaScript

thanks, there is shorter code:)

    
var top = document.body.scrollTop
          || window.pageYOffset 
          || (document.body.parentElement
              ? document.body.parentElement.scrollTop
              : 0
              );

Kieran
March 22, 2010

# re: Retrieving Browser Scroll Position in JavaScript

FireFox using pageYOffset which is a non-standard tag (so much for FireFox always following standards).

they do...
document.documentElement.scrollTop

works in FF, IE6+...

just so ya kno ;)

Dave
August 04, 2010

# re: Retrieving Browser Scroll Position in JavaScript

> Man what a pain in the ass this is
Any post that begins with those words earns an instant +1

forozco
January 13, 2011

# re: Retrieving Browser Scroll Position in JavaScript

Count me like another saved soul from the hell of browser programming, thanks to your example code.

Stephen McNutt
January 25, 2011

# re: Retrieving Browser Scroll Position in JavaScript

I'm editing my elementary school's SharePoint 2010 webpage, and I've got a .htm file that's referenced by a Content Editor web part. If I run the .htm page by itself, I can get the scroll position in any browser (using the tricks found here and elsewhere), but when I view the page as a whole (the page on our school website that contains the web part that refers to my .htm file), I get zero for every scroll position property I could find on the Internet (document.body.scrollTop, window.page&Offset, window.scrollY, document.documentElement.scrollTop, document.body.parentElement.scrollTop).

I can't edit the larger page. Am I just out-of-luck?

Thanks,
Steve

David Schlum
December 19, 2011

# re: Retrieving Browser Scroll Position in JavaScript

I know this is kind of old but I thought I would share what has worked for me. I am using jQuery for everything except for IE8 and lower. Per the suggestion above, I am using document.documentElement.scrollTop for anything IE pre-version 9.0.

//Return integer of current scroll bar position from the top of the page.
function scrollPosition() {
    return Math.max($(window).scrollTop(), document.documentElement.scrollTop /* <= IE8 */);
}


Hope this helps prevent a few hours of banging your head against your cube wall!

-David

West Wind  © Rick Strahl, West Wind Technologies, 2005 - 2024