Dean Elliott
Dean Elliott

Reputation: 729

jQuery. Sticky header on scroll. Stop effects on every scroll

I'm currently using this snippet to make the header of my page "sticky" whenever a user scrolls past a certain distance;

$(window).scroll(function() {

var headerheight = $("header").height();
var header = $(document).scrollTop();

if (header > height-75 ) {
    $('header').addClass('sticky');
    $('body').css("padding-top", headerheight);
    $('.sticky').css('top', 0);
} else {
    $('header').removeClass('sticky');
    $('body').css("padding-top", 0);
    $('header').css('top', 25);
}

The only problem is that the .sticky class is being applied on EVERY scroll past the specified distance and is causing me problems when I want to apply easing effects to it. So basically what I want is for the .sticky class to be applied once, when the page is scrolled past a certain point. How can I achieve that with the current code? Or would I have to start from scratch?

Upvotes: 0

Views: 400

Answers (1)

LeGEC
LeGEC

Reputation: 51840

Just check if the class is present or not :

if (header > height-75 ) {
    if ( !$('header').hasClass('sticky') ){
        $('header').addClass('sticky');
        $('body').css("padding-top", headerheight);
        $('.sticky').css('top', 0);
    }
} else {
    if ( $('header').hasClass('sticky') ){
        $('header').removeClass('sticky');
        $('body').css("padding-top", 0);
        $('header').css('top', 25);
    }
}

Upvotes: 2

Related Questions