Sticky header ignoring offset when smooth scrolling anchor link is clicked

Sticky header ignoring offset when smooth scrolling anchor link is clicked

I'm using smooth scrolling anchor links in a sticky header that is fixed to the top of the page when it scrolls to the top of the screen, otherwise it is positioned statically on the page.

The problem I'm having is the anchor links in the sticky header (the header being static at this stage) when clicked scroll you down correctly but ignore the offset on the page (offset being placed so it compensated for the height of the fixed header), scrolling you past the desired content. This doesn't happen when the .sticky class is applied and the links are clicked when the header is fixed. Anyone any thoughts on how to fix this?

The code I'm using for the sticky header and smooth scrolling is as follows:

  • $(document).ready(function () {
    1.       var move = function () {
    2.         var st = $(window).scrollTop();
    3.         var ot = $("#scroller-anchor").offset().top - 139;
    4.         var s = $("#scroller");
    5.         if (st > ot) {
    6.           s.addClass('sticky').offset().top - 139;
    7.         } else {
    8.           if (st <= ot) {
    9.             s.removeClass('sticky');
    10.           }
    11.         }
    12.       };
    13.       $(window).scroll(move);
    14.       move();
    15.     });
    16.     $(document).ready(function () {
    17.       var headerHeight = $("div#scroller").height();
    18.       $('a[href*=#]:not([href=#])').click(function () {
    19.         if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '')
    20.             || location.hostname == this.hostname) {
    21.           var target = $(this.hash);
    22.           target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
    23.           if (target.length) {
    24.             $('html,body').animate({ scrollTop: target.offset().top - 170 }, 1500 );
    25.           }
    26.           $('html,body').animate({ scrollTop: target.offset().top - 170 }, 1500);
    27.         }
    28.       });
    29.     });

    Any help you be very much appreciated!