I recently had to build a quick “scroll to top” function for our Staff Directory web part to solve a problem of the dynamically loading user profiles displaying out of view when users were scrolled too far down the page.
In typical SharePoint fashion, what initially seemed like a 2 minute task turned into a major investigative effort that lasted a few hours — ok, including this blog post :)
The default SharePoint 2010 page is split in two: the static header/ribbon bar at the very top of the page, and the main content/workspace area (‘s4-workspace’ is the client id). The main workspace area scrolls on its own, while the header bar remains fixed in position.
This would not typically be a problem, if Microsoft had used simple CSS position:fixed for the header bar. Instead we’ve got an overflowed div as the main content area.
This means that using a standard ‘jump to anchor tag’ (i.e. default.aspx#element) is out of the question. According to this blog post by Kyle Schaeffer, standard scrolling is disabled by default on SharePoint’s body tag.
Solution: Scroll To Top Of Page
document.getElementById(‘s4-workspace’).scrollTop = 0;
Bonus: Scroll To Top Of Element
Here’s how to scroll to the top of a specific element on your SharePoint page:
document.getElementById(‘s4-workspace’).scrollTop = document.getElementById(‘yourelement’).offsetTop;
This is essentially telling the s4-workspace container, “Hey, s4-workspace! Yeah I’m looking at you. Set your scroll position to that of this element here.”
NOTE: I had to set position:relative on the target element so that it gained a offsetTop value.