Yahya Essam Yahya Essam - 2 months ago 18
Javascript Question

change navbar color while scrolling

I Just did that way with pure javascript to change navbar color after scrolling,
it worked with google chrome without any problem
but when I tried to test it at firefox
it's not working with it.
anyone can give me any advice about this ?
thanks in advance.



var myNav = document.getElementById("nav");

window.onscroll = function () {
"use strict";
if (document.body.scrollTop >= 280) {
myNav.classList.add("scroll");
} else {
myNav.classList.remove("scroll");
}
};

body {
margin:0;
padding:0;
height:4000px;
}
.nav {
position:fixed;
width:100%;
height:60px;
background-color:#111;
transition:all .5s ease-in-out;
}
.scroll {
background-color:transparent;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="nav" class="nav"></div>




Answer

Try this.

JavaScript:

$(function() {
 $(window).on("scroll", function() {
    if($(window).scrollTop() > 50) {
        $("#navbar").addClass("scroll");
    } else {
        //remove the background property
       $("#navbar").removeClass("scroll");
    }
 });
});

CSS:

.nav {
background-color:#111;
transition:all .5s ease-in-out;
}
.scroll {
background-color:transparent;
}