Navbar changing color to scroll

-1

I tried to make a navbar that at the beginning of the page is transparent and when scrolling the scrool it changes the nav background to black (ex).

code:

*{
	padding: 0px;
	margin: 0px;
	box-sizing: border-box;
}
.header{
	width: 100%;
	height: 1000px;
	background-image: url(../6.jpg);
	background-size: cover;
}
.navbar{
	width: 100%;
	padding: 20px;
	position: fixed;
	top:0px;
	text-align: center;
	transition: .5s;
}
.navbar ul li{
	list-style-type: none;
	display: inline-block;
	padding: 10px 50px;
	color: white;
	font-size: 24px;
	font-family: sans-serif;
	cursor: pointer;
	border-radius: 10px;
}	
.navbar ul li:hover{
	background: orange;
}
.box{
	width: 80%;
	height: 2000px;
	background: green;
	margin: 20px auto;
	
}
<!doctype html>
<html><head>
        <meta charset="utf-8">
        <title>Documento sem título</title>
        <link rel="stylesheet" type="text/css" href="css/normalize.css" />
        <link rel="stylesheet" type="text/css" media="screen" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"/>
        <link rel="stylesheet" type="text/css" media="screen" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css"/>
        <link rel="stylesheet" type="text/css" href="css/css.css" />
    </head>
    <body>

	<div class="header">
	<div class="navbar">
		<ul>
			<li>Home</li>
			<li>Loja</li>
			<li>Contato</li>
			<li>Faq</li>
		</ul>
	</div>
	</div>
<div class="box">
		</div>

		
		<script>
		var nav = document.getElementById('nav');
		window.scroll=function(){
			if(window.pageYOffset>100){
				
				nav.style.background = "#007bff";
				
			}
			else{
				nav.style.background = "transparent";
			}
		}
		</script>
		
    </body>
</html>
    
asked by anonymous 03.01.2018 / 13:59

2 answers

1

The problem was that you did not put the event in the scroll

var nav = document.getElementById('nav');
window.addEventListener("scroll", function(event) {
            if(window.pageYOffset>100){

                nav.style.background = "#007bff";

            }
            else{
                nav.style.background = "transparent";
            }
        });
    
03.01.2018 / 14:46
1

use

document.body.onscroll = () => { //... função igual aqui ... } 

And missing ID on navbar

<div class="navbar" id="nav">
    
03.01.2018 / 14:10