Reputation: 847
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.
Upvotes: 0
Views: 3088
Reputation: 4305
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;
});
Upvotes: 1