Search code examples
jqueryjquery-animateoffsetonscrollscroll-position

Fixed Header Hiding Top of Content


I am working on a website that has a fixed header at the top. However when I navigate to the anchors, the beginning content is hidden by the header. Is there a better way to offset with the code that I'm using. I think it has something to do with the lines below. The whole script is at the fiddle below.

$('a[href^="#"]').on('click', function (e) {
    e.preventDefault();
    $(document).off("scroll");

    $('a').each(function () {
        $(this).removeClass('active');
    })
    $(this).addClass('active');
    var target = this.hash;
    $target = $(target);
    $('html, body').stop().animate({
        'scrollTop': $target.offset().top
    }, 500, 'swing', function () {
        window.location.hash = target;
        $(document).on("scroll", onScroll);
    });
});

https://jsfiddle.net/QuirkCHROMA/d5pp652r/2/


Solution

  • You can add your scrollPosition and the height of the nav bar (80px) so it changes once the bottom of the nav hits that section:

    JS Fiddle

    if (refElement.position().top <= scrollPosition + 80 && refElement.position().top + refElement.height() > scrollPosition + 80 )
    

    And for the scroll to section. Subtract the height of the nav bar:

    $('html, body').stop().animate({
         'scrollTop': $target.offset().top - 80
    }, 500, 'swing', function () {
        window.location.hash = target;
        $(document).on("scroll", onScroll);
    });
    

    Caching the Height - as recommended by Joseph Marikle

    Another thing you can do is set the height as variable instead of manually putting 80 everywhere that its needed. This will also allow you to change the height of the nav without having to go back and edit your JS. To do so:

    Catch the height of the nav in a variable when the document is loaded or resized:

    $(window).on('load resize', function () {
        headerHeight = $('header').height();
    });
    

    and input that variable name everywhere "80" would have been placed.

    JS Fiddle - With variable