Scroll to element on page, and then run callback
<p>I am trying to use jQuery's <code>.animate</code> to scroll to an element on a page, and then execute a callback.</p>

<p>After searching around, I found this function:</p>

<pre><code>function scrollToElement(selector, callback){
    var animation = {scrollTop: $(selector).offset().top};
    $('html,body').animate(animation, 'slow', 'swing', callback);
}
</code></pre>

<p>This correctly scrolls to the element defined by 'selector', but callback is called twice (because <code>$('html,body')</code> contains 2 elements).</p>

<p>I tried changing</p>

<pre><code>$('html,body').animate
</code></pre>

<p>to:</p>

<pre><code>$(document).animate
</code></pre>

<p>and:</p>

<pre><code>$(window).animate
</code></pre>

<p>but, neither of those do anything.</p>

<p>I also tried changing the function to this:</p>

<pre><code>$('html').animate(animation, 'slow', 'swing', function(){
    $('body').animate(animation, 'slow', 'swing', callback);
});
</code></pre>

<p>but, this made the browser run the 1st animation and then the 2nd, so I had wait for both to run before the callback was ran (I dont't want that).</p>

<p>I figured out that <code>$('body').scrollTop()</code> only works in Chrome, and <code>$('html').scrollTop()</code> only works in Firefox.</p>

<p>So, is there a way (without needing to download a jQuery plugin) for me to scroll to a specific element in both Chrome and Firefox (I don't care about IE), and have a callback executed (once)?</p>

<p><strong>EDIT</strong>:</p>

<p>I made a crude fix by making a boolean to check if the callback ran already, and if it was, don't run it again.</p>

<pre><code>function scrollToElement(selector, callback){
    var animation = {scrollTop: $(selector).offset().top};
    var callback_running = false;
    $('html,body').animate(animation, 'slow', 'swing', function(){
        if(typeof callback == 'function' &amp;&amp; !callback_running){
            callback_running = true;
            callback();
        }
    });
}
</code></pre>
