JQuery animation delay on scroll

I have a pivot header collapsing when I scroll down, however I have a lag from returning it to full size by returning back to the top of the page. It seems to get worse as I scroll further.

I have Javascript:

$(document).ready(function () {
    $("header").animate({
        height: "140px"
    }, 200);
    $("header>h2").show(200);
});

$(window).scroll(function () {
    if ($(document).scrollTop() > 0) {
        $("header").animate({
            height: "70px"
        }, 200);
        $("header>h2").hide(200);
    } else {
        $("header").animate({
            height: "140px"
        }, 200);
        $("header>h2").show(200);
    }
});

      

I don't seem to get the same issue if I set the animation time to 0, so I guess these are animated issues.

Is there any lag associated with them, like having to wait for someone to finish doing the next one? If it is (or any other reason for it), is it possible to overcome it and still have animation?

There's a JSFiddle here

+3


source to share


2 answers


The problem is that on every scroll, the animation starts with a 200ms transition. These queues and processes are one by one, so you see the lag. You can stop any existing animations on every scroll:

$ ("heading") stop () ;.

Your complete code:



$(document).ready(function () {
    $("header").animate({
        height: "140px"
    }, 200);
    $("header>h2").show(200);
});

$(window).scroll(function () {
    $("header").stop();
    if ($(document).scrollTop() > 0) {
        $("header").animate({
            height: "70px"
        }, 200);
        $("header>h2").hide(200);
    } else {
        $("header").animate({
            height: "140px"
        }, 200);
        $("header>h2").show(200);
    }
});

      

The spell is here: http://jsfiddle.net/u06sg6a2/

+1


source


This is because the scroll event is fired constantly, so the animation function is also called. But this is not necessary, since after scrollTop

greater than 0 and the title is hidden, the title will remain that way and there is no reason to animate. One easy solution is to change your code with the following:

http://jsfiddle.net/v6rspv0k/



$(document).ready(function () {
    $("header").animate({
        height: "140px"
    }, 200);
    $("header>h2").show(200);
});
var headerNotShown = false;
$(window).scroll(function () {
    if (!headerNotShown&&$(document).scrollTop() > 0) {
        console.log("animation1");
        $("header").animate({
            height: "70px"
        }, 200);
        $("header>h2").hide(200);
        headerNotShown = true;
    } else if(headerNotShown&&$(document).scrollTop() ===0){
        console.log("animation2");
        $("header").animate({
            height: "140px"
        }, 200);
        $("header>h2").show(200);
        headerNotShown=false;
    }
});

      

+2


source







All Articles