Animating Header on Scroll with jQuery

Animating Header on Scroll with jQuery
0.0 0

#1

Here’s my personal portfolio codepen: http://codepen.io/XenoCoder/pen/oYwjwP

I had a script in jQuery that made the header hide and show based on when the user is scrolling. (If the user is scrolling, hide. When he isn’t, show.) However, I later decided that the quick appearance and disappearance of the header looked awful, so I added a simple animation using its opacity to give the header a fade in and fade out effect. However, this made it all go kaput, and I have no idea why. Although, I do have a hunch that it has something to do with the timers…there’s a timer for the scrolling and timers for the animations…


Here’s the specific code that I’m looking at (line 1 of JavaScript):

$(window).scroll(function() {
  var header = $("header");
  header.animate({opacity: 0}, 200);

  clearTimeout($.data(this, "scrollTimer"));

  $.data(
    this,
    "scrollTimer",
    setTimeout(function() {
      header.animate({opacity: 1}, 200);
    }, 200)
  );
});

#2

The scroll event is fired multiple time when you scroll up/down quickly. But your animations are also queued up so when it finally “catches up” when you stopped scrolling, you get this rapid fadeIn, fadeOut, fadeIn, fadeOut… i.e. going kaput.

Anyways, from a usability point of view, hiding the header and then showing it again doesn’t make sense.

An alternative will be to have a tall header, and when you scroll down the page, you change your tall header into a narrow one. Then when a user scrolls back up to the top of the page, you animate the header to show the tall version again.


#3

Something like

  $(document).on("scroll", function(){
    
    var startScroll = $(document).scrollTop();
    
    if(!$("header").hasClass("fadeHeader")){
      $("header").addClass("fadeHeader");
      return;
    }
    
    setTimeout(function(){
      if($(document).scrollTop() == startScroll){
        $("header").removeClass("fadeHeader");
      }
    }, 200);
  });

In CSS

 header{
   transition: opacity 2s;
  }


.fadeHeader{
  opacity: 0;
}

If you’re interested in doing a project that involves more complex scroll-dependent animation, I recommend learning both ScrollMagic and GSAP.


#4

@owel Thanks for the explanation, that made sense. I knew it had something to do with the timers. As for the usability, I thought of that a while back, but the fact that I couldn’t figure this out bothered me, so I wanted to at least understand what was going on before I changed it. Thanks for clearing things up!

@jx2bandito Ah, that makes perfect sense. Thanks for the code, I’ll give it a shot!