Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Lauren Schaller
Lauren Schaller
9,614 Points

Question about scrollTop() & offset().top

I am trying to create a nav bar that is down 500px from the top of the page, but once you scroll down to it, it becomes fixed at the top.

Originally I had the following code:

$(window).scroll(function() {
    if ($(document).scrollTop() > 500) {
        $nav.addClass('fixed');
    }
    else {
        $nav.removeClass('fixed');
    }
});

and

.fixed {
    position: fixed;
    top: 0;
    z-index: 1;
}

However, my page is responsive and the nav bar will not always be 500px down the page. Therefore, I used .offset().top to trigger the fixed class when scrolling reaches the top of my nav bar.

$(window).scroll(function() {
    var $navTop = $nav.offset().top;
    if ($(document).scrollTop() > $navTop) {
        $nav.addClass('fixed');
    }
    else {
        $nav.removeClass('fixed');
    }
});

The issue is that the nav bar flickers terribly when you scroll. I tried replacing .offset() with .position(), which gets rid of the flicker, but it keeps the nav bar fixed for longer than it should when scrolling back up past its original position.

1 Answer

Maybe ask on stackoverflow.. You will get better answers