I am trying to use jQuery .animateto scroll to an element in a page and then call back.
After searching, I found this function:
function scrollToElement(selector, callback){
var animation = {scrollTop: $(selector).offset().top};
$('html,body').animate(animation, 'slow', 'swing', callback);
}
This scrolls correctly to the element defined by 'selector', but the callback is called twice (because it $('html,body')contains 2 elements).
I tried to change
$('html,body').animate
at
$(document).animate
and
$(window).animate
but not one of them does 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 launch the 1st animation, and then the second, so I waited until both were launched before the callback was executed (I don't want this).
I realized that $('body').scrollTop()it only works in Chrome, and $('html').scrollTop()it only works in Firefox.
, ( jQuery), Chrome, Firefox ( IE) ( )?
, , , , , .
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();
}
});
}