Search code examples
javascriptheadersticky

Javascript Sticky nav scrollTo


so I got this sticky header that works great the only problem I have is when I press a link and the screen scrolls down it overlaps my content so I need to set a -47px height or something like that so the # it scrolls to get below the menu and not under it.

My code

$(document).ready(function() {  
var stickyNavTop = $('.header').offset().top;  

    var stickyNav = function(){  
        var scrollTop = $(window).scrollTop();  

        if (scrollTop > stickyNavTop) {   
            $('.header').addClass('sticky');
        } else {  
            $('.header').addClass('sticky');   
        }  
    };  

    stickyNav();  

    $(window).scroll(function() {  
        stickyNav();  
    });  
}); 

$(document).ready(function() {
        var pull        = $('#pull');
            menu        = $('nav ul');
            menuHeight  = menu.height();

        $(pull).on('click', function(e) {
            e.preventDefault();
            menu.slideToggle();
        });
        $(closenav).on('click', function(e) {
            e.preventDefault();
            menu.slideToggle();
        });

        $(window).resize(function(){
            var w = $(window).width();
            if(w > 760 && menu.is(':hidden')) {
                menu.removeAttr('style');
            }
        });
    });

Sorry if i'm not clear enough and need to explain it in another way. Please keep in mind I'm a JS rookie!

Thank you!


Solution

  • var $root = $('html, body');
    $('a').click(function() {
        var href = $.attr(this, 'href');
        $root.animate({
            scrollTop: $(href).offset().top -47
        }, 500, function () {
            window.location.hash = href;
        });
        return false;
    });
    

    add this within your $(document).ready(function(){});