I am trying to use jQuery’s .animate to scroll to an element on a page, and then execute a callback.
After searching around, I found this function:
function scrollToElement(selector, callback){
var animation = {scrollTop: $(selector).offset().top};
$('html,body').animate(animation, 'slow', 'swing', callback);
}
This correctly scrolls to the element defined by ‘selector’, but callback is called twice (because $('html,body') contains 2 elements).
I tried changing
$('html,body').animate
to:
$(document).animate
and:
$(window).animate
but, neither of those do anything.
I also tried changing the function to this:
$('html').animate(animation, 'slow', 'swing', function(){
$('body').animate(animation, 'slow', 'swing', callback);
});
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).
I figured out that $('body').scrollTop() only works in Chrome, and $('html').scrollTop() only works in Firefox.
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)?
EDIT:
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.
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' && !callback_running){
callback_running = true;
callback();
}
});
}
I think this should work too