reknirt reknirt - 6 months ago 22
jQuery Question

Why does smooth scroll flash before scrolling?

I'm building a single page website that is broken up into sections via anchor tags, chiaroscuro.telegraphbranding.com. 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.

Max Max
Answer

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.