3

I am trying to get my navbar to change colour when a user scrolls down the page. Im trying to do this in Bootstrap 5, i've looked at a few videos and posts and all of the examples i've found dont seem to be working with Bootsrap 5. I want the navbar to change from a transparent background, to a white one when the user scrolls down past the hero image. Code is below if anyone can help?

HTML

  <!-- Navbar -->
  <nav class="navbar navbar-expand-lg navbar-light bg-white fixed-top">
    <div class="container">
      <a class="navbar-brand" href="#">Portfolio</a>
      <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav"
        aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
      </button>
      <div class="collapse navbar-collapse" id="navbarNav">
        <ul class="navbar-nav ms-auto">
          <!-- Dropdown -->
          <li class="nav-item dropdown ms-auto">
            <a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" role="button"
              data-bs-toggle="dropdown" aria-expanded="false">
              My Projects
            </a>
            <ul class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
              <li><a class="dropdown-item" href="#ms1">Project 1</a></li>
              <li><a class="dropdown-item" href="#ms2">Project 2</a></li>
              <li><a class="dropdown-item" href="#ms3">Project 3</a></li>
              <li><a class="dropdown-item" href="#ms4">Project 4</a></li>
            </ul>
          </li>
        </ul>
      </div>
    </div>
  </nav>

CSS Code

.bg-white {
  background: green !important;
  transition: 1.5s ease-in;
}

.bg-white.scrolled {
  background: red !important;
}

JavaScript

$(window).scroll(function(){
  $('nav').toggleClass('scrolled', $(this).scrollTop() > 500);
  });
smcgdub
  • 31
  • 1
  • 5
  • Please have a look at [this SO thread](https://stackoverflow.com/questions/23706003/changing-nav-bar-color-after-scrolling). – Marco Rapaccini Jan 12 '22 at 21:24
  • @smcgdub your code seems to work fine. Are you sure you're scrolling past 500 pixels? Try adding `console.log($(this).scrollTop());` inside the scroll event handler. – obscure Jan 12 '22 at 21:26
  • So I ran that code and im getting the following error Uncaught ReferenceError: $ is not defined at index.html:281:5 Which is referring to this line of code: $(window).scroll(function () { I tried doing this in bootstrap 4 and it worked no problem, it just seems to be an issue in bootstrap 5? I think its something to do with the .scrolled – smcgdub Jan 13 '22 at 16:20
  • Managed to solve it, i needed to insert the following – smcgdub Jan 13 '22 at 17:34
  • Does this answer your question? [Changing nav-bar color after scrolling?](https://stackoverflow.com/questions/23706003/changing-nav-bar-color-after-scrolling) – vivalldi Jan 13 '22 at 18:11

0 Answers0