Robson
Robson

Reputation: 1277

Navbar show/hide on scroll like pulsing fade effect

I have a problem with my JS script, which hide my navbar on scroll down and show it on scroll up.

The problem is that navbar show and hide again and again ang again smometimes on scrolling up and the same for scrolling down.

Additionally, when I scroll up to the top of page, navbar is hide on top.

How can i fix this problem with my script ?

Here's my code:

var lastScrollTop = 0;
$(window).scroll(function() {
    var currentScrollTop = $(this).scrollTop();
    if (currentScrollTop > lastScrollTop) {
        $(".header").fadeOut();
    } else {
        $(".header").fadeIn();
    }
    lastScrollTop = currentScrollTop;
});

Upvotes: 0

Views: 295

Answers (1)

dreamweiver
dreamweiver

Reputation: 6002

Your code is triggering multiple scroll events until the scroll operation is not stopped, so what you need to do is to trigger your target event handler only when the scroll operation is completely halted, this is done by a technique called debouncing logic.

function debounce(func, wait, immediate) {
var timeout;
return function() {
    var context = this, args = arguments;
    var later = function() {
        timeout = null;
        if (!immediate) func.apply(context, args);
    };
    var callNow = immediate && !timeout;
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
    if (callNow) func.apply(context, args);
 };
};

// call debounce logic by passing target event handler
var optimisedFunc= debounce(function() {
   var currentScrollTop = $(this).scrollTop();
   if (currentScrollTop > lastScrollTop) {
      $(".header").fadeOut();
   } else {
      $(".header").fadeIn();
   }
   lastScrollTop = currentScrollTop;
}, 250);

$(window).scroll(function(){
      optimisedFunc();
});

The above debouncing logic does more than delayed execution, refer this for more information.

Upvotes: 1

Related Questions