JasonDaly.name

PHP, Ruby, Symfony, Rails, Doctrine, MooTools. Web Development.
May 5, 2010

Shifting the Window to Display Anchors Below Fixed Element

When browsing to an anchor within an page, all browsers (that I know of) scroll the page to the anchored element such that the element is at the very top of the visible browser window. This is a problem when a site design includes a fixed element at the top of the browser window. A little bit of Javascript (via MooTools) can fix this:

var AnchorFix = new Class({

  Implements: Options,

  options: {
    fixed_element: null
  },

  initialize: function(options){
    this.setOptions(options);

    this.applyTrigger();
  },

  /**
   * Applies the onhashchange event to the window
   * to listen for a new anchor being browsed to by the user
   */
  applyTrigger: function(){
    var fn = window.onhashchange || $empty;
    window.onhashchange = function() {
        fn();
        this.reScrollWindow();
    }.bind(this);
  },

  /**
   * Calculates the proper scroll point for the window based
   * on the height of the fixed element at the top of the page,
   * allowing the anchored element to be visible under the fixed
   * element
   */
  reScrollWindow: function(){
    var hash = window.location.hash.trim().substring(1);
        var element = ($(hash) != null) ? $(hash) : $(document.body).getElement('*[name="' + hash + '"]');

        if (element != null) {
        var position_y = element.getPosition().y;
        var bar_height = $(this.options.fixed_element).getSize().y

        window.scrollTo(0, (position_y - bar_height - 5));
      }
  }
});

// Instantiate a new instance of the class to get started
var fixMyAnchors = new AnchorFix({$('idOfTheFixedElement')});

Not all browsers support the Javascript onhashchange event (read: IE7 and earlier). A bit of the applyTrigger() code above was modified from MooHistory, and with a bit of tweaking if desired, support could be added to the code above for earlier versions of IE (check out their source to see how they handle IE6/7).

Tags: Mootools browsers javascript css onhashchange code