artemean
artemean

Reputation: 855

jQuery animate() fires after a pause on scrolling

I'm trying to make a simple sticky navbar that is invisible on top of a page and slides down when you scroll the page down. First I used scrollUp() / ScrollDown() but I don't like the way it looks because it animates the height and I want to animate position. It just looks different. So I decided to use animate() and apply it to margin-top.

HTML:

<div>
...lots of blocks and text
</div>
<div class="top_bar">some elements here</div>

CSS:

.top_bar {
    margin-top: -70px; 
    height:70px; 
    position: fixed; 
    width: 100%; 
    left: 0; 
    top: 0; 
    z-index: 1000; 
    background:#156373; 
    color: #fff; 
    text-align:center;
}

JS:

var stickyBar = function(){
    var scroll = $(window).scrollTop();
    if (scroll > 100) {
        $('.top_bar').animate({
            "margin-top": 0
        },"fast");
        } else {
        $('.top_bar').animate({
            "margin-top": -70
        },"fast");
    }
};
$(window).scroll(function() {  
    stickyBar();  
});

The problem is it animates after some pause. I scroll a page to the very top, it waits for a second and then the top_bar is animated off. I scroll the page down, it waits for a second and then the top_bar is animated on.

I don't understand where this pause is coming from... Please advise what am I doing wrong?

http://jsfiddle.net/hc31qds5/1/

Upvotes: 1

Views: 460

Answers (1)

Tomanow
Tomanow

Reputation: 7377

You probably want to use CSS3 transitions for the most responsive effect. Try this:

CSS

.top_bar {
    max-height: 0;
    position: fixed;
    width: 100%;
    left: 0;
    top: 0;
    z-index: 1000;
    background:#156373;
    color: #fff;
    text-align:center;
    transition: all 0.4s cubic-bezier(0, 1, 0.5, 1);
}
.top_bar.sticky {
    max-height: 70px;
    height: 70px;
}

JS

$(window).scroll(function () {
    if ($(this).scrollTop() > 100) {
        $('.top_bar').addClass("sticky");
    } else {
        $('.top_bar').removeClass("sticky");
    }
});

FIDDLE

UPDATE

Here it is with jquery animate without the delay:

$(window).scroll(function () {
    if ($(this).scrollTop() > 100) {
        $('.top_bar').stop().animate({
            "margin-top": 0
        }, 200);
    } else {
        $('.top_bar').stop().animate({
            "margin-top": -70
        }, 200);
    }
});

FIDDLE

You just needed to make sure to stop() the previous animation.

Upvotes: 3

Related Questions