Highlight an item on the page and then run the callback

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();
        }
    });
}
+3
5

,

function scrollToElement(selector, callback){
    var animation = {scrollTop: $(selector).offset().top};
    $('html,body').animate(animation, 'slow', 'swing', function() {
        if (typeof callback == 'function') {
            callback();
        }
        callback = null;
    });
}
+3

jQuery 1.5 ( ), $.Deferred.

$.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');
});

, .

+1

$(document.body).animate( ... )
0

DIV, DIV? , (, HTML BODY, )

0

html, body. , ( ) .

function scrollToElement(selector, callback){
    var scrollElem='html';
    //animate body for webkit browsers that don't support html animation
    if($.browser.webkit){ 
        scrollElem='body';
    }
    var animation = {scrollTop: $(selector).offset().top};
    $(scrollElem).animate(animation, 'slow', 'swing', callback);
}

webkit "html", "scrollElem". , (html body) (, Opera).

0
source

Source: https://habr.com/ru/post/1792598/


All Articles