Reputation: 1
I know this has been asked but I am unsure of how to apply answers to my site. I have a fixed navbar in BOOTSTRAP and the scroll to a certain div goes just a BIT too far so that the top of the div is blocked by the fixed nav.
//jQuery for page scrolling feature - requires jQuery Easing plugin
$(function() {
$('.page-scroll a').bind('click', function(event) {
var $anchor = $(this);
$('html, body').stop().animate({
scrollTop: $($anchor.attr('href')).offset().top
}, 1500, 'easeInOutExpo');
event.preventDefault();
});
});
Upvotes: 0
Views: 1358
Reputation: 6442
The section $($anchor.attr('href')).offset().top
is used to calculate how far down the page to scroll the body.
You can add or subtract from this number to align things better.
You could measure the height of the nav and use that figure to subtract from the offset().top
value
$(function() {
var navHeight = $('#fixedNav').outerHeight(); // adjust this for your nav id
$('.page-scroll a').bind('click', function(event) {
var $anchor = $(this);
$('html, body').stop().animate({
scrollTop: $($anchor.attr('href')).offset().top - navHeight
}, 1500, 'easeInOutExpo');
event.preventDefault();
});
});
You could then also update this value when the window resizes, such that if your navigation changes height (say if a line break occurs) this updates your fixed value
$(function() {
var navHeight = $('#fixedNav').outerHeight(); // adjust this for your nav id
$(window).bind('resize', function(){
navHeight = $('#fixedNav').outerHeight(); // adjust this for your nav id
});
$('.page-scroll a').bind('click', function(event) {
var $anchor = $(this);
$('html, body').stop().animate({
scrollTop: $($anchor.attr('href')).offset().top - navHeight
}, 1500, 'easeInOutExpo');
event.preventDefault();
});
});
If you want to go with this updating on resize event solution i would also suggest implementing some kind of throttler (so that it only updates the height value once every 100ms for example, rather than on each event trigger), this should boost performance. Have a look at something like Ben Almans Throttle/Debounce library
Upvotes: 3