I am using the following code to have a smooth scroll to section when we click a navigation menu item:
// handle links with @href started with '#' only
$(document).on('click', 'a[href^="#"]', function(e) {
// target element id
var id = $(this).attr('href');
// target element
var $id = $(id);
if ($id.length === 0) {
return;
}
// prevent standard hash navigation (avoid blinking in IE)
e.preventDefault();
// top position relative to the document
var pos = $id.offset().top;
// animated top scrolling
$('body, html').animate({scrollTop: pos}, 2000);
});
However, I needed to put the header on position fixed, with a height of 90px and now when we scroll to the section, the beginning of the section is hidden behind the section. Is it possible to keep my code and include for example a certain distance from the top?
I tried to put a parameter on the offset method but it didn't work:
// handle links with @href started with '#' only
$(document).on('click', 'a[href^="#"]', function(e) {
// target element id
var id = $(this).attr('href');
// target element
var $id = $(id);
if ($id.length === 0) {
return;
}
// prevent standard hash navigation (avoid blinking in IE)
e.preventDefault();
// top position relative to the document
var pos = $id.offset(top:120).top;
// animated top scrolling
$('body, html').animate({scrollTop: pos}, 2000);
});
Am I doing something wrong?
CodePudding user response:
var pos = $id.offset().top - 90;
Is it what you mean?