One of the problems is that you're executing an animation of 400ms for every time your user scrolls the page, this generates a very long queue of effects which have no visible effect, e.g. animating to 1
opacity for each time the scroll
event fires with scrollTop > 50
, adding a very long queue of invisible effects until the fading out effect takes place.
A simple way to remedy that is using .stop(true)
before executing the fadeTo
, this way the element effects queue will be always cleared before executing the given animation.
$(window).on('scroll', function() {
if ($(this).scrollTop() > 50) {
$("#header").stop(true).fadeTo(400, 0.5);
} else {
$("#header").stop(true).fadeTo(400, 1);
}
});
But even so you will still be executing animations unnecessarily, so I'd recommend using .data
to store the faded state and only animate when necessary:
$(window).on('scroll', function() {
var header = $("#header");
if ($(this).scrollTop() > 50) {
if (!header.data('faded')) header.data('faded', 1).stop(true).fadeTo(400, 0.5);
} else if (header.data('faded')) {
header.data('faded', 0).stop(true).fadeTo(400, 1);
}
});
ps. I've inverted your opacity values as your question's code's logic didn't correspond to your desired behavior.