Search code examples
javascriptjqueryheaderfixed

Fixed header wont keep fixed after window is reloaded in same position


I have this code to add a fixed header class every time the window is scrolled. The problem is that when the window is loaded for anchor links, lets say, 100px from the top, it will load the header in its original appearance, and it will only add the fixed class after window is scrolled. How can I fix that?

$(window).on("load resize", function () {
        var headerTop = $(".header").offset().top;
        var headerHeight = $(".header").outerHeight();
        $(window).on("scroll", function () {
            var scrollTop = $(window).scrollTop();
            if (scrollTop > headerTop) {
                $('.header').addClass("fixed");
            } else {
                $('.header').removeClass("fixed");
            }
        });
    });

Solution

  • You are using $(".header").offset().top; to compare in if (scrollTop > headerTop) condition, you should compare with if (scrollTop > headerHeight)

    $(".header").outerHeight(); variable has actual height of header element.

    Please check below code :

    $(window).on("load resize", function () {
        var headerTop = $(".header").offset().top;
        var headerHeight = $(".header").outerHeight();
        $(window).on("scroll", function () {
            console.log('scroll...');
            var scrollTop = $(window).scrollTop();
            if (scrollTop > headerHeight) {
                console.log('applied fiexed');
                $('.header').addClass("fixed");
            } else {
                $('.header').removeClass("fixed");
                console.log('removed fiexed');
            }
        });
    });
    .header{
        border:solid 1px red;
        height:50px;
        width:501px;
        background-color:#808080;
        font-size:20px;
    }
    
    .fixed{
        position:fixed;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <div class="header">This is header</div>
    Something line 1<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />
    Something line 2<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />
    Something line 3<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />
    Something line 4<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />
    Something line 5