Search code examples
jqueryoffsetscrollto

jQuery, click to add class to offset 49px


On my one page website, I am using the Scroll To functionality that scrolls to different parts of the website.

There is a fixed navigation that offsets by 49px so it can land on the section perfectly.

$('nav a').click(function() {
    $('html, body').animate({scrollTop: ($(this.hash).offset().top - 49)}, 1800,
        function() {}
    );
    return false;
});

But I have a blog on the website. So what I want to happen is when I click on the fixed navigation from the blog it will offset the navigation by 49px, currently it doesnt reconise the offset. I have tried this but doesnt work.

$('nav a.secondary-link').click(function(event) {
    $('html, body').animate({scrollTop: ($(this.hash).offset().top - 49)}, 1800,
        function() {}
    );
    return false;
});

You can see my workings here: If you view the news page first you can notice that the section doesn't recognise the 49px offset.

http://aspe.fishtankcreative.co.uk/newcastle-falcons/blog/falcons-to-support-primary-school-sport-with-new-initiative.php

http://aspe.fishtankcreative.co.uk/newcastle-falcons/

Please help. Thanks


Solution

  • It happens because in the blog post, the links, are ACTUAL links, meaning they change page, causing a complete request to the server and a reload of all Javascript. The click event is gone by the time the next page is up, which is where you want to scroll. Luckily we get a hash with us, which gives us a hook we can use to animate afterwards.

    This should do it for you :)

    $(document).ready(function(){
        var idOfSection = window.location.hash.substring(1);
        var $sectionToScrollTo = $('#'+idOfSection);
        if($sectionToScrollTo.length > 0){
            var offset = $sectionToScrollTo.offset().top-49; 
            $('html, body').animate({scrollTop: offset },1800);
        }
    });
    

    If you want it to scroll from the top, add: $('html, body').animate({scrollTop: 0},0); as the first thing in the if statement.


    To improve further

    $(document).ready(function(){
        var sectionId = window.location.hash;
        scrollToSection(sectionId);
    
        $('body').on('click', 'nav a', function(){
            var secId = this.hash;
            scrollToSection(secId);
        }
    });
    
    function scrollToSection(sectionId){
        var $sectionToScrollTo = $(sectionId);
        if($sectionToScrollTo.length > 0){
            var offset = $sectionToScrollTo.offset().top-49; 
            $('html, body').animate({scrollTop: offset },1800);
        }
    }
    

    Note that I haven't tested the second code example.