jqueryhtmlcssheaderfading

Second Header fading in or fading out depending of scrolling


Im coding a website and I want to have 2 headers..one showing when user is on top of the page and second one when you scroll. I tried to do that with jquery and it works like its supposed to do(on top of the page is "top", when I scroll down "top2"), but when I scroll back to the top, the second one(that's supposed to fade out) filckers/blinks one time then fades out.

$(function () {
    'use strict';
    $(window).scroll(function () {
        var scrollval = $(window).scrollTop();
        if (scrollval >= 50) {
            $("#top").fadeOut('slow');
            $("#top2").fadeIn('slow');
       }
       if (scrollval <= 10) {
           $("#top").fadeIn('slow');
           $("#top2").fadeOut('slow');
       }
    });
});

HTML

<div id="top">....</div>
<div id="top2>...</div>

CSS

#top {
    background:red;
    width:100%; 
    height: 50px; 
} 
#top2 {
    display: none; 
    position:fixed; 
    top:0; 
    left: 0; 
    background:black; 
    width:100%; 
    height: 50px; 
    margin:0 auto; 
}

Solution

  • The issue is due to .fadeOut('slow') and .fadeIn('slow');..the code below will fix the issue

    html

    <div id="top"></div>
    <div id="top2"></div>
    

    JS

    $(function () {
        'use strict';
        $(window).scroll(function () {
            var scrollval = $(window).scrollTop();
            if (scrollval >= 50) {
                $("#top").css("opacity", 0);
                $("#top2").css("opacity", 1);
            }
            if (scrollval <= 10) {
                $("#top").css("opacity", 1);
                $("#top2").css("opacity", 0);
            }
        });
    });
    

    CSS

    #top {
        background:red;
        width:100%; 
        height: 50px; 
    } 
    #top2 {
        opacity: 0;
        position:fixed; 
        top:0; 
        left: 0; 
        background:blue; 
        width:100%; 
        height: 50px; 
        margin:0 auto; 
        transition: opacity 1s ease;
    }
    

    Thanks !