0

I'm using the following jQuery click function to jump to various sections of a long scrolling page (by anchor ID) that also factors in-- and thus offsets by-- the height of a fixed navigation header:

$('#nav a').click(function(){
    var el = $(this).attr('href');
    var elWrapped = $(el);

    scrollToDiv(elWrapped,75);
    return false;

});
function scrollToDiv(element,navheight){
    var offset = element.offset();
    var offsetTop = offset.top;
    var totalScroll = offsetTop-navheight;

    $('body,html').animate({
    scrollTop: totalScroll
    }, 500);
}

This works very well, however, the only downside with this approach is I have to define an amount by which to offset the scroll from the page top-- in this case, by 75px, i.e the height of the fixed header. For cases in which the height of the fixed header may change-- say for mobile via media query-- this height will likely be inaccurate, and the links won't offset by the correct amount of space.

Thus, I'm wondering how I might change/augment this function by calculating the actual height of the header and offset by that amount, plus say 10 additional pixels to account for section padding.

Thanks for any assistance here.

1 Answer 1

1

You can get the height of the header when a button is clicked.

$('#nav a').click(function(){
    var el = $(this).attr('href');
    var elWrapped = $(el);
    var header_height = $('#header-id-goes-here').height() + 10;
    //var header_height = $('#header-id-goes-here').outerHeight(); You might need outerHeight if you have padding and borders

    scrollToDiv(elWrapped,header_height);
    return false;
});
Sign up to request clarification or add additional context in comments.

2 Comments

One other related question-- if I wanted to add a static value of additional pixels to height() or outerHeight() is that possible to specify for var header_height?
Ah that's simple enough! Thanks David.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.