Reputation: 47
I have a smooth scroll function that is used to scroll to specific sections of my page when links are clicked on. However, when it automatically scrolls to a section, it does not account for the height of my fixed navbar, which ends up covering up some of the content. I would like to calculate the height of the navbar and subtract it from the scroll position within my current function
$(function() {
$('a[href*="#"]:not(.carousel-control)').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html, body').animate({
scrollTop: target.offset().top
}, 1000);
return false;
}
}
});
});
Upvotes: 2
Views: 1154
Reputation: 42374
You need to add the height of your navbar to scrollTop: target.offset().top
. This is an integer value, and can be calculated by simply referencing the .height()
of the navbar DOM element itself.
Here's an example assuming a navbar with the class of navbar
:
scrollTop: target.offset().top + $('.navbar').height()
Hope this helps! :)
Upvotes: 0