Skip to content

Instantly share code, notes, and snippets.

@coffeencoke
Created June 7, 2012 19:26
Show Gist options
  • Save coffeencoke/2891030 to your computer and use it in GitHub Desktop.
Save coffeencoke/2891030 to your computer and use it in GitHub Desktop.

Revisions

  1. coffeencoke revised this gist Jun 7, 2012. 2 changed files with 14 additions and 1 deletion.
    1 change: 0 additions & 1 deletion do_it.js
    Original file line number Diff line number Diff line change
    @@ -1,4 +1,3 @@

    $(function(){
    $('.subnav').fixElementOnScroll(45, 'subnav-fixed');
    $('.sidebar-nav').fixElementOnScroll(113, 'fixed');
    14 changes: 14 additions & 0 deletions fix.css
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,14 @@
    .sidebar-nav.fixed{
    position: fixed;
    top: 99px;
    left: 20px;
    width: 19.5%;
    }

    .subnav-fixed{
    position: fixed;
    top: 40px;
    height: 40px;
    left: 0;
    right: 0;
    }
  2. coffeencoke created this gist Jun 7, 2012.
    5 changes: 5 additions & 0 deletions do_it.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,5 @@

    $(function(){
    $('.subnav').fixElementOnScroll(45, 'subnav-fixed');
    $('.sidebar-nav').fixElementOnScroll(113, 'fixed');
    });
    26 changes: 26 additions & 0 deletions jquery.fixElementOnScroll.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,26 @@
    /*
    * This will add a class to all matching elements when they reach a specific point when scrolling
    * and will remove the class after going back to the point. Similar to how twitter bootstrap's secondary
    * nab works on this page (http://twitter.github.com/bootstrap/scaffolding.html) as you scroll.
    * Notice how it snaps to the top and remains fixed.
    */
    (function( $ ){
    $.fn.fixElementOnScroll = function(heightOffset, classForFixing) {
    if(this.length > 0){
    var $win = $(window);
    var topOfFixPoint = this.length && this.offset().top - heightOffset;
    var $this = this;
    $win.on('scroll', function(){
    var isFixed = $this.hasClass(classForFixing);
    var i, scrollTop = $win.scrollTop();

    var shouldFixElement = scrollTop >= topOfFixPoint && !isFixed;
    var shouldUnfixElement = scrollTop <= topOfFixPoint && isFixed;

    if (shouldFixElement || shouldUnfixElement) {
    $this.toggleClass(classForFixing);
    }
    });
    }
    };
    })( jQuery );