Home » Jquery » javascript – How to have a Bootstrap navbar scroll with the user?

javascript – How to have a Bootstrap navbar scroll with the user?

Posted by: admin February 22, 2020 Leave a comment


It’s been a while since I’ve last programmed anything. I want to replicate the effect used by the navigation bar here. However the closest I’ve managed to come to an actual piece of code is:

$('body').on('scroll', function() {
    $('.navbar').css("bottom", $('.navbar').outerHeight(true));

How can I fix this to replicate the effect in the link above?

How to&Answer:

It’s easy. Just see this example here:


Just put the CSS class fixed-top to your nav element, like in the example:

<nav class="navbar navbar-expand-md navbar-dark fixed-top bg-dark">
  <a class="navbar-brand" href="#">Fixed navbar</a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  <div class="collapse navbar-collapse" id="navbarCollapse">
    <ul class="navbar-nav mr-auto">
      <li class="nav-item active">
        <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
      <li class="nav-item">
        <a class="nav-link" href="#">Link</a>
      <li class="nav-item">
        <a class="nav-link disabled" href="#">Disabled</a>
    <form class="form-inline mt-2 mt-md-0">
      <input class="form-control mr-sm-2" type="text" placeholder="Search" aria-label="Search">
      <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>

If you want your navbar stick to the browser edge right after scrolling over it, use the CSS class sticky-top, e.g.

    <nav class="navbar sticky-top navbar-light bg-light"><a class="navbar-brand" href="#">Sticky top</a></nav>

See https://getbootstrap.com/docs/4.0/components/navbar/#placement