I found myself working on a user profile management tool this week. This tool had dozens of internal links to other areas of the user profile.
During testing, I became quickly annoyed by the fact that each time I clicked a link to another part of the profile, the page scroll position was "reset" to the top.
Within this tool, I'd ideally like it to maintain the scroll position between page loads.
For the purposes of this article, I'll call this technique persistent scroll location.
Why not fragment identifiers?
For "one-off" links, this technique is perfect and is exactly what fragment identifiers were meant to do.
There are two problems with fragment identifiers though:
- They may require additional markup. The id attribute may need to be added to an element that didn't otherwise require it.
- Difficult to maintain. If you have 100 links containing the same fragment identifier, they would all need to be changed if the id of the referenced element is changed.
Session Storage might work
Issues with Session Storage:
- It's not available on legacy browsers.
- It doesn't allow us to share a link that includes the scroll location (as fragment identifiers do).
Passing in the Query String
For example:
http://www.sitekickr.com/?scroll=190
Issues with appending a query string parameter:
- This might create duplicate content issues from an SEO perspective if too many variations are spread around the web. Fragment identifiers appear to be "SEO-safe". All of my research indicates that Google ignores the fragment identifier.
- A scroll query string parameter would conflict with a document fragment identifier if there was one.
Dynamic Fragment Identifiers
I'll call this technique Dynamic Fragment Identifiers. The premise is simple:
- "Hijack" selected link click events.
- When those link click even handlers are called:
- If the link does not already contain a fragment identifier
- Retrieve the current window scroll position
- Append the scroll position in a fragment identifier
- If the link does not already contain a fragment identifier
- On page load, if a scroll position-related fragment identifier is detected:
- Obtain the scroll position from the fragment identifier
- Scroll the window to that position
Example: http://www.sitekickr.com/#sy-350 (meaning: scroll y-axis 350 pixels)
The Code
After writing this post, I realized how simple the implementation would be. So I whipped up a quick jQuery plugin. You can't go wrong with a 538-byte plugin (I think).
http://www.sitekickr.com/code/jquery/jquery.AntiScroll/
On GitHub https://github.com/lanasa/antiscroll