Bryce Johnson
Bryce Johnson

Reputation: 6931

How can I keep this jQuery scroll event from firing constantly?

I'd like a navigation bar to stick (position:fixed) when it hits the top of the window. But I also want the element to go back to normal positioning if the user scrolls back up.

The following code makes the element stick, but as you scroll, the event keeps firing, causing the element to flash in and out. If I remove the 'else removeClass()', it's smooth (and stops flashing) but the element stays fixed after I scroll back up to the top. Thoughts?

Relevant CSS:

.fixed-object {
    width:100%;
    background-color:tomato;
}

.stick {
    position:fixed;
    top:0;
}

jQuery:

   $(window).scroll(function(){

    var elementDepth = $('.fixed-object').offset().top;
    var scrollDepth = $(window).scrollTop();

    if (scrollDepth >= elementDepth) {
        $('.fixed-object').addClass('stick');
    } else {
        $('.fixed-object').removeClass('stick');
    }


});

Upvotes: 0

Views: 644

Answers (1)

rynhe
rynhe

Reputation: 2529

Make it as simple.....

Declare the elementDepth as GLOBAL variable... it will work

var elementDepth = $('.fixed-object').offset().top;
  $(window).scroll(function(){
    var scrollDepth = $(window).scrollTop();

    if (scrollDepth >= elementDepth) {
        $('.fixed-object').addClass('stick');
    } else {
        $('.fixed-object').removeClass('stick');
    }
});

Live Demo

Upvotes: 2

Related Questions