Search code examples
jquerymenuresizewindowposition

JQuery How to resize div while scrolling top or down


I have problem with resizing div while screen is on the top of the page or anythere else.

$(window).scroll(function() {
    top = $('html').scrollTop();
    setTimeout(
    function() 
    {
        if(top == 0)
        {
            $(".navbar").animate({height:'70px'});
        }
        else
        {
            $(".navbar").animate({height:'43px'});
        }
    }, 100);

});

Div .navbar is resizing while I'm scrolling down, but it's not getting to the original height while screen is on the top. How to resize it back? Also if you have any ideas how to make it in different way - post it.

Thanks.


Solution

  • Several scroll events are being triggered, causing these animations to queue, which could cause a long delay before the navbar changes height. Try clearing the timer each time it's triggered.

    var scrollTimer = null;
    $(window).scroll(function() {
        var top = $(document).scrollTop(); // use document (suggested by seva.rubbo)
                                           // use local var (suggested by Sam Battat)
    
        clearTimeout(scrollTimer);
        scrollTimer = setTimeout(
        function() 
        {
            if(top == 0)
            {
                $(".navbar").animate({height:'70px'});
            }
            else
            {
                $(".navbar").animate({height:'43px'});
            }
        }, 100);
    });
    

    Fiddle: http://jsfiddle.net/jzsxjw7o/1/