0

I want to add a callback onto this animate function --

$("a#goto-3").click(function() {
    $('html, body').animate({
       scrollTop: $("#landpoint-3").offset().top}, 1000, 'easeInOutCubic'
    );
    return false; 
});

I can do it onto the scrollTop with this...

$("a#goto-2").click(function() {
    $('html, body').animate({
       scrollTop: $("#landpoint-2").offset().top}, 1000, 'easeInOutCubic', function() {
         document.write('complete');  
       });
    return false; 
});

..but having no luck getting it onto the animate function - I know this one should be super straightforward.... thanks in advance..

2 Answers2

1
$("a#goto-3").click(function() {
    $('html, body').animate({
       scrollTop: $("#landpoint-3").offset().top}, 1000, 'easeInOutCubic', function() { callback stuff here; }
    );
    return false; 
});

Make sure you only animate ONE element, you are animating on both html and body.

See this example: http://jsfiddle.net/HQUaD/2/

Barry Chapman
  • 6,690
  • 3
  • 36
  • 64
  • Hi this is still callback is still on the scrollTop, and not the animate itself - if I put a document.write in there as in ... $("a#goto-3").click(function() { $('html, body').animate({ scrollTop: $("#landpoint-3").offset().top}, 1000, 'easeInOutCubic', function() { callback stuff here; } ); return false; }); the result writes 'completecomplete' ... ? – Chris Carruthers Feb 12 '13 at 14:46
  • Its because you are animating two elements (html and body) – Barry Chapman Feb 12 '13 at 14:55
  • ahah - this error is a result of animating two elements at once - see here http://stackoverflow.com/questions/8790752/callback-of-animate-gets-called-twice-jquery – Chris Carruthers Feb 12 '13 at 14:56
-1
$('html, body').animate({
   scrollTop: $("#landpoint-3").offset().top}, 1000, 'easeInOutCubic', function() {
       // animation completed code
   }
);

See the docs here

Or you could use .when() like this:

$.when($('html, body').animate({
   scrollTop: $("#landpoint-3").offset().top}, 1000, 'easeInOutCubic'))
.then(function() {
    // both animations completed code!
});
Matt Burland
  • 44,552
  • 18
  • 99
  • 171
  • Yeah, I guess it's the 2 element problem (`html` and `body`). What you can do is use `.when()` and `.then()` to add a callback when *both* animations are finished. I'll update my answer in a moment. – Matt Burland Feb 12 '13 at 15:11