I am currently working on improving the functionality of my fixed navigation bar at the top of the screen. When a link in the nav bar is clicked, it scrolls to a specific section using this code:
$('a[href^="#"]').bind('click.smoothscroll',function (e) {
e.preventDefault();
var target = this.hash,
$target = $(target);
$('html, body').animate({
'scrollTop': $target.offset().top - 45
}, 400, 'swing', function () {
window.location.hash = target;
});
});
});
The issue I'm facing is that when it scrolls to the section, it shifts down on the screen and covers content initially. However, if I click on the same section again, it goes to the correct spot without any shifting. How can I make sure it goes to the correct spot on the first click?
If I remove the "- 35" part from the animate() function, it does not shift down but I need to offset the nav bar to prevent it from covering content. What could be causing this jumping/shifting behavior? Any advice or insights would be appreciated. Thank you!
Note: I also have another piece of code, but I am unsure if it contributes to the issue:
$(document).ready(function(){
var offset = $(".navbar").offset().top;
$(window).scroll(function() {
if ($(window).scrollTop() >= offset) {
$('.navbar').addClass('navbar-fixed');
}
});
UPDATE: By delving deeper into jQuery's animate details, I realized that the "complete" parameter (a function to call once the animation is complete) I was using was unnecessary, so I removed it from my code.