Search code examples
jquerycssheaderfade

Have header fade out then in after appending class


I have a small script that allows my header to append and remove a subclass upon scrolling the page.

However, the transition is hard, and I'd like to have the header variants fade from one to another.

I can't figure out how to get it to fade. It either flashes in and out, or blinks then fades. I was wondering if someone could help me out.

The jquery code I have is below (in it's broken state)

function init() {
window.addEventListener('scroll', function(e){
    var distanceY = window.pageYOffset || document.documentElement.scrollTop,
        shrinkOn = 100,
        header = document.querySelector("#header");
    if (distanceY > shrinkOn) {
        $("header").addClass("smaller").fadeIn(400);
    } else {
        if ($("header").hasClass("smaller")) {
            $("header").fadeOut(400).removeClass("smaller").fadeIn(400);
     }
    }
});
}
window.onload = init();

I want the header to fade out, the append the .smaller class, then fade back in.

And vise-versa.

I hope my question makes sense.


Solution

  • I was able to figure it out, but this has spawned a new question which will be posted later. Here is my soloution below:

    $(document).ready(function() {
        /*
            navOffset - The distance in which to trigger the events
            scrollPos - The position Y that the page has been scrolled
        */
    
      var navOffset = 5 /*$("header").offset().top;*/
    
        $(window).scroll(function(){
        var scrollPos = $(window).scrollTop();
        $("header").stop(true);
    
            if (!$("header").hasClass("smaller") || scrollPos < navOffset) {
                if (scrollPos > navOffset) {
                    $("header").fadeTo(400, 0, function() {
                        $("header").addClass("smaller");
                    });
                    $("header").fadeTo(400, 1); 
                } else {
                    $("header").fadeTo(400, 0, function (){
                        $("header").removeClass("smaller");
                    });
                    $("header").fadeTo(400, 1);
                }
            }
        });
    });