0

I'm working on a site which requires a sticky nav bar, which should 'pop out' of the header when the user scrolls down the page. It should then return to its original positioning within the header when the user scrolls back to the top.

Here is the JSFiddle.

My problem is that my .sticky class is not being removed when the user scrolls back to the top of the page. I have already researched other questions regarding jQuery's removeClass() not working, but none of the proposed solutions to these questions have worked for my case.

I considered whether my 'if' statement condition was causing the problem but when tracing out the scrollTop() numerical values, everything seems to be correct. The 'else' condition definitely runs (I verified this with more console logs), but the jQuery removeClass() does not.

var stickyHeaderOffsetValue = $('#sticky-container').offset().top;
var currentOffsetPosition = $(window).scrollTop();

if (currentOffsetPosition >= stickyHeaderOffsetValue) {
    $('#sticky-container').addClass('sticky');
} else {
    $('#sticky_navigation').removeClass(); // this didn't work
}
Community
  • 1
  • 1
Candlejack
  • 448
  • 10
  • 23

2 Answers2

2

http://jsfiddle.net/fS3Tr/4/

A few things, firstly you need to hold the "home" position of the header. Once it's fixed it'll never compute correctly.

if (!window.homePosition) window.homePosition = $('#sticky-container').offset().top;

Secondly you removed the class from the wrong tag :)

$('#sticky-container').removeClass('sticky');
PeteAUK
  • 968
  • 6
  • 16
1

You're close. The header is not resetting because after you assign it the sticky class, it loses its top offset. I would simply reset the top offset when you remove the sticky class.

Also, removeClass() expects the name of class to remove.

stickyHeaderHandler();

// ON WINDOW SCROLL
    $(window).scroll(function(){
        stickyHeaderHandler();
    });

function stickyHeaderHandler() {
    var stickyHeaderOffsetValue = $('#sticky-container').offset().top;
    var currentOffsetPosition = $(window).scrollTop();

    //console.log(currentOffsetPosition + " + " + stickyHeaderOffsetValue);
    if (currentOffsetPosition >= stickyHeaderOffsetValue) {
        $('#sticky-container').addClass('sticky');
    } else {
        // Remove sticky class & Reset the top offset
        $('#sticky_navigation').removeClass('sticky')
                               .offset({ top: "104px", left: offset.left})
    }
}

Here's a working fiddle.

James Hill
  • 60,353
  • 20
  • 145
  • 161