How to make navbar change on scroll from transparent to coloured

Viewed 41

I'm trying to change my navbar from transparent to coloured when I scroll. I used using video tutorial to help, and did as the instructor said, but I did not get the same result. Here is my html, css and javascript (i added it just above the closing tag for body)

$(window).scroll(function(){
  $('nav').toggleClass("scrolled", $(this).scrollTop()>50);
})
body{
  height:2000px
}

.bg-dark{
  background: transparent !important;
}

.bg-dark-scrolled{
  background-color: rgba(15, 14, 14, 0.838) !important;
}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css">

<nav class="container navbar navbar-expand-lg bg-dark pt-4 fixed-top bgcolor">
<!--content of navbar-->
</nav>

<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

May I get an explanation on why it's not working, and what to do to fix it?

1 Answers

Because you didn't add the scrolled class, and also the bootstrap .bg-dark background-color override the one declared in your CSS, you need to increase the precedence by adding more class .navbar.bg-dark

    $(window).scroll(function(){
        $('nav').toggleClass("scrolled", $(this).scrollTop()>50);
    })
body {
  height: 2000px;
}

.navbar.bg-dark{
  background-color: transparent !important;
  color: white;
}

.bg-dark.scrolled {
  background: #000 !important;
}

.bg-dark-scrolled{
background-color: rgba(15, 14, 14, 0.838) !important;
}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<nav class="container navbar navbar-expand-lg bg-dark pt-4 fixed-top bgcolor">
        //content of navbar
        </nav>

Related