Spiegel Spiegel - 1 month ago 5
Javascript Question

Event scroll up and fixed header jquery

I have a function

$(document).ready(function () {
var lastScroll = 0;
$(window).scroll(function(event){
var st = $(this).scrollTop();
if ((lastScroll - st) == 5) {
$("header").css("position", "fixed");
}
else {
$("header").css("position", "absolute");
}
lastScroll = st;
});
});


But I want, when I scroll up on 5px, header again shows.
How I can follow event scroll up 5px?

Answer

You're updating your lastScroll to often, to make sure it has scrolled past a certain delta (in your case 5px) you should include that clause before checking if the user has scroll up or down.

This tutorial may help you, but I also created a fiddle with an updated version of your code.

But it would go like this:

 $(document).ready(function () {
    var lastScroll = 0;
    $(window).scroll(function(event){
        var st = $(this).scrollTop();
        // Make sure they scroll more than delta
        if(Math.abs(lastScroll - st) <= 5)
            return;

        if (st < lastScroll) {
           $("header").css("position", "fixed");
        } else {
          $("header").css("position", "absolute");
        }
        lastScroll = st;
    });
  });