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 () {
- var move = function () {
- var st = $(window).scrollTop();
- var ot = $("#scroller-anchor").offset().top - 139;
- var s = $("#scroller");
- if (st > ot) {
- s.addClass('sticky').offset().top - 139;
- } else {
- if (st <= ot) {
- s.removeClass('sticky');
- }
- }
- };
- $(window).scroll(move);
- move();
- });
- $(document).ready(function () {
- var headerHeight = $("div#scroller").height();
- $('a[href*=#]:not([href=#])').click(function () {
- if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '')
- || location.hostname == this.hostname) {
- var target = $(this.hash);
- target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
- if (target.length) {
- $('html,body').animate({ scrollTop: target.offset().top - 170 }, 1500 );
- }
- $('html,body').animate({ scrollTop: target.offset().top - 170 }, 1500);
- }
- });
- });
Any help you be very much appreciated!