Skip to content

Instantly share code, notes, and snippets.

@scottrippey
Created August 24, 2012 17:43

Revisions

  1. scottrippey created this gist Aug 24, 2012.
    55 changes: 55 additions & 0 deletions FixedHeader.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,55 @@
    Uverse.widgets.FixedHeader = new Class({
    Implements: [ Options ]
    , el: null
    , sectionsNavigationSelector: '.sections-navigation'
    , _fixedZIndex: 15
    , _sectionsNavigation: null
    , _regularBodyPaddingTop: null
    , _regularMastheadMarginTop: null
    , _onScrollHandler: function() {
    var bodyPaddingTop;
    // If the scroll value is greater than the sectionsNavigation offset top
    // we should fix it. The reason to use > instead of === is that browsers
    // won't trigger this for every scrolled pixel.
    if(window.scrollY > this._sectionsNavigation.offsetTop) {
    // We change the style of `el`:
    // - `width: 100%` because we want this to occupy all the screen wide.
    // - `position: fixed` to fix it, duh.
    // - `margin-top' is the weird one, we want to push the header top
    // but we want to add padding to avoid a nasty "jump"
    // caused by missing floating (fixing).
    // - `z-index: 10` because we need to float over every element.
    this.el.setStyles({
    'width': '100%',
    'position': 'fixed',
    'margin-top': -2 * this._sectionsNavigation.offsetTop,
    'z-index': this._fixedZIndex
    });
    // Set the body top padding to the offset of the navigation in order
    // to avoid a "jump" caused by floating the masthead.
    bodyPaddingTop = this._sectionsNavigation.offsetTop;
    } else {
    // If we are in a static safe zone, we can go ahead and return everything
    // to the normal state.
    this.el.setStyles({
    'position': 'static',
    'margin-top': this._regularMastheadMarginTop
    });
    bodyPaddingTop = this._regularBodyPaddingTop;
    }
    // @note: Should we move this inside the if statements?
    document.body.setStyle('padding-top', bodyPaddingTop);
    }
    , initialize: function(el, options) {
    this.el = $(el);
    this.setOptions(options);

    // Select the sections navigation…
    this._sectionsNavigation = el.getElement(this.sectionsNavigationSelector),
    // …and save the regular paddings and margins that will change on scroll.
    this._regularBodyPaddingTop = document.body.getStyle('padding-top');
    this._regularMastheadMarginTop = el.getStyle('margin-top');

    document.addEvent('scroll', this._onScrollHandler.bind(this));
    }
    });