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 Challenge

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, standard scrolling is disabled by default on SharePoint’s body tag.

So as a user, when I first visit a page that is presented in the SharePoint 2010 interface, scrolling is disabled. As the content is loading, I am unable to view anything below the fold, and must wait for a JavaScript function to execute and allow me to view overflow content.Furthermore, this breaks the functionality of any anchors on your page. For instance, if you click on a link that includes #comments on the end of the URL, users will not be able to see the comments section of the page that subsequently loads. Instead, pages are always displayed starting at the top of the page. This is definitely not a practice in progressive enhancement.

Solution: Scroll To Top Of Page

The solution was to use a simple JavaScript command assigned to the onclick of my source element, which when clicked set the scroll position of the s4-workspace container element to 0:

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.