Rob Rob - 1 month ago 7
HTML Question

Fade background colour up/down when scrolling from the top

I have a menu strip that is fixed to the top of the page, at the point when you scroll 50px from the top a class is added to it - which in turn changes the colour. And vice versa when you get back to the top.

At the moment it just adds a class when you're 50px from the top - which visually causes the colour to flick between one or the other.

Is there a way to fade from one into another when you hit 50px from the top, then reverse the process when you scroll up the page?

This is my code:

// Change menu colour when it moves from the top of the page
$(window).on("scroll", function() {
if($(window).scrollTop() > 50) {
$(".headerStrip").addClass("activated");
} else {
//remove the background property so it comes transparent again (defined in your css)
$(".headerStrip").removeClass("activated");
}
});

.headerStrip{
background:rgba(239, 239, 239, 0.5);
padding:0;
position: fixed;
width: 100%;
z-index: 9999;
}
.activated {
background:rgba(239, 239, 239, 0.9);
}

Answer

You can add transition property in your css.

And in your JQuery code change only the background property.

Example

$(window).on("scroll", function() {
    if($(window).scrollTop() > 50) {
        $(".headerStrip").css("background","rgba(239, 0, 0, 0.5)");
    } else {
       $(".headerStrip").css("background","rgba(239, 239, 239, 0.5)");
    }
});
.headerStrip{
background:rgba(239, 239, 239, 0.5);
padding:0;
position: fixed;
width: 100%;
z-index: 9999;
transition:background 2s;
}
.activated {
background-color:red;    
}

.body{
height:4000px;  
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="headerStrip">
  test
</div>
<div class="body"></div>