Reputation: 3868
I have an issue with a smooth scroll for anchor tags on the sidenav. I am using bootsrap scrollspy with affix. The header is position fixed, Hence when we click on side menu anchor it navigates to specific ID. The issue is when it scrolls to the ID the header overlaps the content so I am adding some offset to scroll but the animation is not smooth it flickers on each click. How can I prevent the flickering and render the animation smoothly. (To view script/HTMl/CSS please use view source)
Update : As I noticed this issue happens when we display the #ID in the URL. Any idea how can can we make it smooth ?
Here is the link with hash appended in URL : http://103.50.162.107/~chaitol4/test/nohash/expertise.html
URL without Hash : http://103.50.162.107/~chaitol4/test/hash/expertise.html
Notice the animation when you click the items on sidenav
My JS :
$(".smooth-scroll").click(function() {
var headerHeight = 60;
$('html, body').stop(true, true).animate({
scrollTop: $(this.hash).offset().top - headerHeight
}, 750);
return false;
});
Updated script :
$(document).ready(function() {
$(".smooth-scroll").on('click', function(event) {
var hash = this.hash;
$('html, body').animate({
scrollTop: $(hash).offset().top - 60
}, 800, function(){
window.location.hash = hash;
event.preventDefault();
});
event.preventDefault();
});
This calculates wrong offset top ( Goes below the menu )
Upvotes: 0
Views: 2705
Reputation: 3677
This is expected. The browser's default behavior would be to snap the scroll to the element with the id matching the hash. Jquery is likely performing the animation but by the time the animation starts your scroll doesn't need to be adjusted.
The solution would be to pick one or the other, scroll to an element using jQuery or scroll to an element with the id and url hash.
Upvotes: 0
Reputation: 128
The problem lies with the hyperlink and the solution is simple.
Replace all your hyperlinks within the li elements of your navigation list with a regular span element and bind a click event to this. In this click event scroll to the specified position and update the querystring. Updating the querystring by javascript does not cause the browser to instantly go to this position, thus enabling the smooth scroll.
The javascript function you need to change the hash, after the smooth scroll, is this:
history.pushState(null, null, '#myhash');
Made a fiddle to illustrate. Note. Pushstate does not work in fiddle due to restrictions. http://jsfiddle.net/xpvt214o/183435/
Upvotes: 0