Saroar Saroar - 2 months ago 11
CSS Question

How to Change Navigation Bar Background with Scroll?

I'm new to web-developing. For one of my projects, I want to change the navigation bar's background when the user scrolls.
I want it to look like exactly this:
https://www.nlogic.co/understanding-vlan-hopping-attacks/

Here's my code:



nav .row {
margin-right: 0px;
}
nav {
border: 2px ridge #999;
position: fixed;
}
nav li {
float: left;
list-style: none;
padding: 20px 30px;
}
nav a {
color: white;
font-size: 20px;
}
.btn button {
background-color: transparent;
color: white;
margin: 10px 30px;
padding: 10px 25px;
border: 2px solid #999;
border-radius: 5px;
}
.btn button:hover {
border: 2px solid white;
border-radius: 10px;
}

<nav class="col-md-12">
<div class="row">
<ul class="col-md-8">
<li><a href="#">About</a>
</li>
<li><a href="#">Contact</a>
</li>
<div class="clearfix"></div>
</ul>
<div class="btn col-md-4">
<button>Sign Up</button>
<button>Sign In</button>
</div>
</div>
</nav>





I am not good at jQuery. In fact, I only know the basics of Javascript. I will be Very Very Grateful if someone can help me here.

Answer

Try this :

$(document).ready(function(){

    $(window).on("scroll",function(){

        if($(document).scrollTop() > 150)
            $(".col-md-12").css({backgroundColor:"gray",position:"fixed"});


        else
             $(".col-md-12").css({backgroundColor:"transparent",position:"absolute"});


    })

})

Final code :

<!DOCTYPE html>
<html lang="en">
<head>
    <style>
        body {
            height: 1500px;
        }
        nav .row{
    margin-right: 0px;
}

nav{
    border: 2px ridge #999;
    position:absolute;
}

nav li{
    float: left;
    list-style: none;
    padding: 20px 30px;
}

nav a{
    color:white;
    font-size: 20px;    
}

.btn button{
    background-color: transparent;
    color: white;
    margin: 10px 30px;
    padding: 10px 25px;
    border: 2px solid #999;
    border-radius: 5px;
}

.btn button:hover{
    border: 2px solid white;
    border-radius: 10px;
}
    </style>
</head>
    
    <body>
        
        <nav class="col-md-12">
    <div class="row">
        <ul class="col-md-8">
            <li><a href="#">About</a></li>
            <li><a href="#">Contact</a></li>
            <div class="clearfix"></div>
        </ul>   
        <div class="btn col-md-4">
            <button>Sign Up</button>
            <button>Sign In</button>
        </div>
    </div>
</nav>
        
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
        <script>
            
    $(document).ready(function(){

        $(window).on("scroll",function(){

            if($(document).scrollTop() > 150)
                $(".col-md-12").css({backgroundColor:"gray",position:"fixed"});


            else
                $(".col-md-12").css({backgroundColor:"transparent",position:"absolute"});


        })

    })
        
        </script>
    </body>
</html>