I am using the following code to animate scroll from a menu link in a navbar on bootstrap:
$("#subnavbar ul li a[href^='#']").on('click', function(e) {
e.preventDefault();
$('html, body').animate({ scrollTop: $(this.hash).offset().top }, 600);
// edit: Opera and IE requires the "html" elm. animated
});
At the moment, the fixed navbar hides the anchor underneath. How can I add an offset of 60px to adjust for this?
I am using the following code to animate scroll from a menu link in a navbar on bootstrap:
$("#subnavbar ul li a[href^='#']").on('click', function(e) {
e.preventDefault();
$('html, body').animate({ scrollTop: $(this.hash).offset().top }, 600);
// edit: Opera and IE requires the "html" elm. animated
});
At the moment, the fixed navbar hides the anchor underneath. How can I add an offset of 60px to adjust for this?
Share Improve this question asked Aug 17, 2013 at 13:06 alias51alias51 8,64822 gold badges106 silver badges185 bronze badges1 Answer
Reset to default 8You need to subtract 60
from the offset().top
of the target element, to allow space for the navbar. I've done this dynamically by getting the height()
of the #subnavbar
so that should you ever need to change it's height in ther future, you don't need to worry about breaking this code.
$("#subnavbar ul li a[href^='#']").on('click', function(e) {
e.preventDefault();
$('html, body').animate({
scrollTop: $(this.hash).offset().top - $('#subnavbar').height()
}, 600);
});