0

I found this solution and need to modify it so that when it hits the footer it unsticks. I know there is no scroll_bottom, so I was thinking of trying to create a variable for the footer, like below. I will keep plugging away, however, was hoping maybe someone could help out.

$(document).ready(function() {
// Cache selectors for faster performance.
var $window = $(window),
    $mainMenuBar = $('#mainMenuBar'),
    $mainMenuBarAnchor = $('#mainMenuBarAnchor');

// Run this on scroll events.
$window.scroll(function() {
    var window_top = $window.scrollTop();
    var window_bottom = $window.height() - this.scrollTop() - this.height(); 
    var div_top = $mainMenuBarAnchor.offset().top;
    if (window_top > div_top) {
        // Make the div sticky.
        $mainMenuBar.addClass('stick');
        $mainMenuBarAnchor.height($mainMenuBar.height());
    }
    else if (window_bottom > div_top) {
     $mainMenuBar.removeClass('stick');
        $mainMenuBarAnchor.height(0);
    }
    else {
        // Unstick the div.
        $mainMenuBar.removeClass('stick');
        $mainMenuBarAnchor.height(0);
    }
});

});

I also found this solution, but can not get it working with jquery 1.7.

Community
  • 1
  • 1

1 Answers1

0

This seems to do the job:

HTML

You said you wanted a solution without using #mainMenuBarAnchor, so delete:

<div id="mainMenuBarAnchor"></div>

from your HTML code.

JS

$(document).ready(function() {
    // Cache selectors for faster performance.
    var $window = $(window),
        $mainMenuBar = $('#mainMenuBar'),
        $menuBarOffset = $mainMenuBar.offset().top,
        window_top = 0,
        footer_offset = $("#footer").offset().top,
        content = $("#content"),
        panel_height = $mainMenuBar.outerHeight()+'px';


    // Run this on scroll events.
    $window.scroll(function() {
        window_top = $window.scrollTop();

        if (window_top >= $menuBarOffset) {
            if (window_top >= footer_offset) {
                // Unstick the div.
                $mainMenuBar.removeClass('stick');
                content.css('margin-top', 0);
            } else {
                // Make the div sticky.
                $mainMenuBar.addClass('stick');
                content.css('margin-top', panel_height);
            }
        }
        else {
            // Unstick the div.
            $mainMenuBar.removeClass('stick');
            content.css('margin-top', 0);
        }
    });
});

The code is a little longer now than before, but that's mainly because I added a few variables in the beginning so that you don't have to calculate some stuff on every scroll (like footer offset, the menu bar offset..).

jsFiddle demo

display-name-is-missing
  • 4,424
  • 5
  • 28
  • 41