Slightly better fragment id scrolling

Disclaimer: This is a useless post to point out and solve a very minor annoyance. That annoyance being how the browser “scrolls” to content based on the URL’s fragment identifier.

Specifically, I speak of that fact that whichever DOM id or anchor tag is targeted by the fragment identifier is brought to the very top of the viewport without any upper padding.

I’d like to see a little padding between the targeted element and the top of the viewport. But, instead of wasting my time making silly suggestions to browser vendors, I decided to write a dozen lines of JavaScript to scratch my itch.

Basically, the JavaScript determines if a fragment identifier is present in the URL. If found, once the the window onload event fires, the browser window is vertically scrolled by 20 pixels to give a little breathing room between the top of the viewport and the content.

That’s it! Here’s the code, and sorry to waste your time with this nonsense 😉

function betterFrag() {

  var PADDING = 20;

  function getScrollY() {
      var scrOfY = 0;
      if( typeof( window.pageYOffset ) == 'number' ) {
        scrOfY = window.pageYOffset;
      } else if( document.body && 
        ( document.body.scrollLeft || document.body.scrollTop ) ) {
        scrOfY = document.body.scrollTop;
      } else if( document.documentElement && 
        ( document.documentElement.scrollLeft || 
        document.documentElement.scrollTop ) ) {
        scrOfY = document.documentElement.scrollTop;
      return scrOfY;

  var y = getScrollY();
  if (y > 0)
    window.scroll(0, y - PADDING);

if (location.hash) {
  window.onload = betterFrag;

Why follow me on Twitter?

  • I tweet about new technologies, services or libraries I find interesting
  • Yeah, sometimes I'll post a pet-peeve or rant about something trivial
  • If I discover something that made my web development life easier, I share it
  • I'll shout out any handy tip that I think might be useful to other devs

Tagged , .

Updated: 2014-08-04

Phil LaNasa follow us in feedly