Friday, December 14, 2012

jQuery animate scrollTop Flicker

Hey everybody,

was doing some scrolling animations on my one-page site using jQuery's animate function.

This is the basics of what I had:


$(function(){
  $("#link").click(function(){ 
    navigateTo(".section");
  });
});

function navigateTo(destination) {
  $('html,body').animate({scrollTop: $(destination).offset().top - 48},'slow');
}

The issue I was seeing is that the animate was happening, but so was a flicker. The flicker was caused by the default behaviour of clicking on a link with href="#". The problem is the default behvaiour of that is to scroll to the top. So it would quickly scroll to the top, then scroll to the destination. Solution? Block the default behaviour by returning false in the event handler of the click.


$(function(){
  $("#link").click(function(){ 
    navigateTo(".section");
    return false;
  });
});

function navigateTo(destination) {
  $('html,body').animate({scrollTop: $(destination).offset().top - 48},'slow');
}

Hopefully that will help some peeps.

1 comment:

Anonymous said...

the return false was what I was after ... thx so much!!!!