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;

Leave a Reply

Your email address will not be published. Required fields are marked *