jQuery script smooth scroll to different sections with a different offset

Viewed 8953

I am using a smooth scroll script for my one page site. It scrolls to each anchor.

Due to the design, I can't have the anchor snap straight to the top of the page. I have had to create hidden anchors that are further up the page so it does not snap exactly to the top.

Here is the script I am currently using:

jQuery(document).ready(function($) {
    $(".scroll").click(function(event){ 
        event.preventDefault();
        $('html,body').animate({
            scrollTop: $('[name="' + this.hash.substring(1) + '"]').offset().top
        }, 500);
    });
});

I have been informed that I can make the offset happen within this script. Rather than having these little hidden anchors everywhere, I can simply add something to the end of top to offset it by a certain number of pixels. It would be top - 250

$('html,body').animate({
    scrollTop:$('[name="' + this.hash.substring(1) + '"]').offset().top - 250
}, 500);

The problem is this would make the offset always be 250px, I need it to be variable so that for example, the portfolio div can be anchored with an offset of 200px, but the contact div only by 50px.

Can anyone help me write some sort of selector into the script that will allow me to adjust this top - [variable] based on which div is being anchored?

2 Answers
Related