Alvin Jones
Alvin Jones

Reputation: 251

Fixed Navigation Menu after Scrolll

I'm trying to create a sticky navigation menu that will be positioned right underneath a banner and when you scroll down and the banner cannot be seen anymore the navigation menu will be fixed at the top of the browser chrome. Here's what I have so far: http://tinyurl.com/bper44a

The CSS is straight forward, the issue may be with my JS:

$(document).ready(function() {
    var s = $(".navMenu");
    var pos = s.position();  
    $(window).scroll(function() {
        var windowpos = $(window).scrollTop();
            if (windowpos >= pos.top) {
                s.addClass("fixedTop"); }
            else {
                s.removeClass("fixedTop"); 
                }
        });
    });

While it works exactly the way on want it in Firefox, I can figure out why it behaves differently in Chrome and Safari (gets into fixed position as soon as you scroll down just a little bit).

Any insight?

Upvotes: 2

Views: 353

Answers (1)

net.uk.sweet
net.uk.sweet

Reputation: 12431

Not sure why it works in firefox, but I think the following will work for all browsers:

$(document).ready(function() {
    var s = $(".navMenu");
    var banner = $("header > img");

    $(window).scroll(function() {
        var windowpos = $(window).scrollTop();
            // if the scroll position is greater than the height of the banner
            // fix the navigation. 
            if (windowpos >= banner.outerHeight()) {
                s.addClass("fixedTop"); }
            else {
                    s.removeClass("fixedTop"); 
                }
            });
        });

Obligatory fiddle here.

Upvotes: 1

Related Questions