Scroll To Element On Page, And Then Run Callback
Solution 1:
I think this should work too
functionscrollToElement(selector, callback){
var animation = {scrollTop: $(selector).offset().top};
$('html,body').animate(animation, 'slow', 'swing', function() {
if (typeof callback == 'function') {
callback();
}
callback = null;
});
}
Solution 2:
If you are using jQuery 1.5 (or can upgrade to it), you can use the new $.Deferred
syntax.
$.fn.scrollToElement = function(selector, callback) {
var def = new $.Deferred(),
el = this;
$('html, body').animate({scrollTop: $(selector).offset().top}, 'slow', 'swing', def.resolve);
if (callback) {
def.promise().done(function(){
callback.call(el);
});
}
};
$('html, body').scrollToElement('#foo', function() {
alert('done scrolling');
});
Because a deferred object can only be resolved once, you can't have more than one call to the callback.
Solution 3:
Have you tried using
$(document.body).animate( ... )
Solution 4:
how about using a DIV that stretches over the full document body and do the animation on that DIV instead? you can't be sure how many more browser issues you can find otherwise (i.e. how many more browsers would not animate HTML nor BODY for instance)
Solution 5:
You should avoid animating both html and body elements. Your page animation will work correctly on every modern or old browser and the callback will run once (as it should) by the addition of a simple condition in your function.
functionscrollToElement(selector, callback){
var scrollElem='html';
//animate body for webkit browsers that don't support html animationif($.browser.webkit){
scrollElem='body';
}
var animation = {scrollTop: $(selector).offset().top};
$(scrollElem).animate(animation, 'slow', 'swing', callback);
}
Only webkit doesn't support "html" animation, so you change the "scrollElem" variable accordingly. In addition, scrolling a single element (html or body) works much better on older browsers (e.g. previous versions of Opera).
Post a Comment for "Scroll To Element On Page, And Then Run Callback"