I'm building a single page website that is broken up into sections via anchor tags. When you click on the nav links it smooth scrolls to the section (only funding areas and about us are complete), however, it seems like about 50% of the time when you click the link, the background image it smooth scrolls to flashes before the jQuery scrolls up or down.
To me it seems like the HTML is trying to immediately go to the anchor, hence the flashing, but then jQuery says, hold up, I need to scroll slowly.
I'm not sure how to resolve this.
jQuery:
// SlowScroll Funding Areas
$(document).ready(function(){
// 'slowScrollTop' is the amount of pixels #teamslowScroll
// is from the top of the document
var slowScrollFunding = $('#funding-areas').offset().top;
// When #anchor-aboutus is clicked
$('#anchor-funding-areas').click(function(){
// Scroll down to 'slowScrollTop'
$('html, body, #home-wrap').animate({scrollTop:slowScrollFunding}, 1000);
});
});
// SlowScroll About Us
$(document).ready(function(){
// 'slowScrollTop' is the amount of pixels #slowScrollTop
// is from the top of the document
var slowScrollTop = $('#about-us').offset().top + 446;
// When #anchor-aboutus is clicked
$('#anchor-aboutus').click(function(){
// Scroll down to 'slowScrollTop'
$('html, body, #aboutus-wrap').animate({scrollTop:slowScrollTop}, 1000);
});
});
I very much appreciate any and all suggestions.
So, if you want to scroll smoothly to that part instead, you first need to reset the scroll position to 0 and then add smooth scrolling. // direct browser to top right away if (window. location. hash) scroll(0,0); // takes care of some browsers issue setTimeout(function(){scroll(0,0);},1);
With smooth scrolling, it slides down smoothly, so you can see how much it scrolls. This might not be a huge deal for you but it is a big deal for users who read a lot of long pages. The choppy scroll might be annoying for a lot of users and that's why people are moving towards the smooth scroll option.
Try adding event.preventDefault();
after your click function.
This stops the link from doing what it is supposed to do (jump to the anchor immediately) and prevents a race condition.
$('#anchor-aboutus').click(function(){
// Scroll down to 'slowScrollTop'
$('html, body, #aboutus-wrap').animate({scrollTop:slowScrollTop}, 1000);
event.preventDefault();
event.stopPropagation();
});
Or even cleaner:
$('#anchor-aboutus').click(function(){
// Scroll down to 'slowScrollTop'
$('html, body, #aboutus-wrap').animate({scrollTop:slowScrollTop}, 1000);
return false;
});
Here's why:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With