Ryan Ryan - 10 months ago 86
Javascript Question

Change Navbar Color on scroll

My navbar cannot change color on scroll, i am already using this script. please help me

$(window).scroll(function() {
if ($(document).scrollTop() > 50) {
$(".navbar-fixed-top").css("background-color", "#f8f8f8");
} else {
$(".navbar-fixed-top").css("background-color", "transparent");

i am using bootstrap

Answer Source

Hope this works, you have to use scrollTop() to get vertical scrollbar position and accordingly made changes in your selected div i.e. over-here is .navbar.

  	var wn = $(window).scrollTop();
    if(wn > 120){
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<nav class="navbar navbar-fixed-top">
  <div class="container-fluid">
    <div class="navbar-header">
      <a class="navbar-brand" href="#">WebSiteName</a>
    <ul class="nav navbar-nav">
      <li class="active"><a href="#">Home</a></li>
      <li><a href="#">Page 1</a></li>
      <li><a href="#">Page 2</a></li> 
      <li><a href="#">Page 3</a></li>