jQuery Animate Body Scroll For All Browsers

It turns out that when trying to use jQuery’s animate to scrollTop on the main body of an html document different browsers require different targets to scroll to. Webkit requires targeting the body of the document while all other browsers that I know of use html. The typical solution is to target both in the same call:

$('html, body').animate({
    scrollTop: '0px','fast', function(){
        // Code to be fired when complete goes here (fired twice)
    }
});

This solution is problematic, however, because even though the scrollTop will only work once, the callback is fired twice. That means that if we were relying on the callback to tell us that the function is complete, our complete function would fire twice. Luckily, there is a relatively simple solution to this problem. Using jQuery’s browser plugin we can have webkit browsers target the body and all others target the html.

// If using a newer version (>= 1.9) of jQuery a separate browser
// plugin is required
$(jQuery.browser.webkit ? "body": "html").animate({
    scrollTop: '0px','fast', function(){
        // Code to be fired when complete goes here
    }
});

This solution worked well for me. I am open to different ideas or solutions if you know of any.