Having trouble with Bootstrap4 sticky-top (sticky navbar) functionality

I have created a navigation bar on my HTML page and applied the Bootstrap 4 class sticky-top to it.

The issue I am facing is that the navbar sticks to the top until half of the screen is scrolled, but then the sticky property stops working and the navbar moves upward as the page is scrolled further.

Why does it work for a limited margin and then suddenly stop working?

I have tried using the navbar-fixed-top class, and also attempted

position:sticky; top:0; width:100%
, but without success.

HTML code for the navbar:

<nav class="navbar navbar-expand-lg navigation navbar-fixed-top" style="position:sticky; top: 0; width:100%;" id="bootnavbar">
      <div class="container">
            <a class="navbar-brand" href="index.php"><i class="fas fa-home"></i></a>
            <button class="navbar-toggler  ml-auto custom-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation" style="font-size:0.85em;">
                  <span class="navbar-toggler-icon"></span>
            </button>

            <div class="collapse navbar-collapse" id="navbarSupportedContent">
                  <ul class="navbar-nav mr-auto">

                        <li class="nav-item dropdown">
                              <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                                    About Us
                              </a>
                              <ul class="dropdown-menu" aria-labelledby="navbarDropdown">
                                    <li><a class="dropdown-item" href="about.php">About</a></li>
                                    <div class="dropdown-divider"></div>
                                    <li><a class="dropdown-item" href="boac.php">Board of Advisory Committee</a></li>
                                    <li><a class="dropdown-item" href="bos.php">Board of Studies</a></li>
                                    <div class="dropdown-divider"></div>
                                    <li><a class="dropdown-item" href="admission.php">Admission</a></li>
                                    <li class="nav-item dropdown">
                                          <a class="dropdown-item dropdown-toggle" href="#" id="navbarDropdown1" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                                                Academic
                                          </a>
                                          <ul class="dropdown-menu" aria-labelledby="navbarDropdown1">
                                                <li><a class="dropdown-item disabled" href="faculty.php">Faculty</a></li>
                                                <li><a class="dropdown-item" href="activities.php">Activities</a></li>
                                          </ul>
                                    </li>
                                    <li><a class="dropdown-item" href="facilities.php">Facilities</a></li>
                              </ul>
                        </li>

                        <li class="nav-item dropdown">
                              <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                                    Courses
                              </a>
                              <ul class="dropdown-menu" aria-labelledby="navbarDropdown">
                                    <li><a class="dropdown-item" href="regular_courses.php">Regular Courses</a></li>
                                    <li><a class="dropdown-item" href="short_term_courses.php">Short Term Courses</a></li>
                              </ul>
                        </li>

                        <li class="nav-item">
                              <a class="nav-link" href="gallery.php" role="button" aria-haspopup="true" aria-expanded="false">
                                    Gallery
                              </a>
                        </li>

                        <li class="nav-item">
                              <a class="nav-link" href="placements.php" role="button" aria-haspopup="true" aria-expanded="false">
                                    Training & Placements
                              </a>
                        </li>
                        <li class="nav-item">
                              <a class="nav-link" href="alumni.php" role="button" aria-haspopup="true" aria-expanded="false">
                                    Alumni
                              </a>
                        </li>

                        <li class="nav-item">
                              <a class="nav-link" href="feedback.php" role="button" aria-haspopup="true" aria-expanded="false">
                                    Feedback
                              </a>
                        </li>

                  </ul>
            </div>
      </div>
</nav>

<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/bootnavbar.js"></script>
<script>
      $(function() {
            $('#bootnavbar').bootnavbar();
      })
</script>

CSS for the navbar:

.navigation {
    background: #020031;
    padding: 0px 23px;
    font-size: 17px;
    z-index: 500;
    box-shadow: 0px 10px 15px -9px;
}

.navbar-brand {
    color: #fff;
}

.navbar-brand:hover {
    color: #fff;
}

.navigation .nav-item .nav-link {
    color: #fff;
    margin-right: 10px;
    padding: 16px;
    text-transform: capitalize;
    font-weight: 500;
}

.navigation li a:hover {
    background: #f6783a;
}

.custom-toggler.navbar-toggler {
    border-color: rgb(255, 255, 255);
}

.custom-toggler .navbar-toggler-icon {
    background-image: url("data:image/svg+xml;charset=utf8,%3Csvg viewBox='0 0 32 32' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath stroke='rgb(255, 255, 255)' stroke-width='2' stroke-linecap='round' stroke-miterlimit='10' d='M4 8h24M4 16h24M4 24h24'/%3E%3C/svg%3E");
}

.nav-switch {
    display: none;
}

.nav-section {
    background: #020031;
}

.nav-section .nav-right {
    float: right;
    padding-top: 23px;
}

.nav-section .nav-right a {
    color: #fff;
    margin-left: 30px;
    font-size: 16px;
}

.main-menu {
    list-style: none;
}

.main-menu li {
    display: inline;
}

.main-menu li a {
    display: inline-block;
    color: #fff;
    font-size: 13px;
    text-transform: uppercase;
    font-weight: 500;
    padding: 25px 20px;
    margin-right: -5px;
    -webkit-transition: all 0.4s ease 0s;
    -o-transition: all 0.4s ease 0s;
    transition: all 0.4s ease 0s;
}

.main-menu li a:hover {
    background: #f6783a;
}

.main-menu li.active a {
    background: #f6783a;
}

bootnavbar.css

.dropdown-menu {
    margin-top: 0;
}
.dropdown-menu .dropdown-toggle::after {
    vertical-align: middle;
    border-left: 4px solid;
    border-bottom: 4px solid transparent;
    border-top: 4px solid transparent;
}
.dropdown-menu .dropdown .dropdown-menu {
    left: 100%;
    top: 0%;
    margin:0 20px;
    border-width: 0;
}

.dropdown-menu > li a:hover,
.dropdown-menu > li.show {
    background: #007bff;
    color: white;
}
.dropdown-menu > li.show > a{
    color: white;
}

@media (min-width: 768px) {
    .dropdown-menu .dropdown .dropdown-menu {
        margin:0;
        border-width: 1px;
    }
}

bootnavbar.js

(function($) {
    var defaults={
        sm : 540,
        md : 720,
        lg : 960,
        xl : 1140,
        navbar_expand: 'lg'
    };
    $.fn.bootnavbar = function() {

        var screen_width = $(document).width();

        if(screen_width >= defaults.lg){
            $(this).find('.dropdown').hover(function() {
                $(this).addClass('show');
                $(this).find('.dropdown-menu').first().addClass('show').addClass('animated fadeIn').one('animationend oAnimationEnd mozAnimationEnd webkitAnimationEnd', function () {
                    $(this).removeClass('animated fadeIn');
                });
            }, function() {
                $(this).removeClass('show');
                $(this).find('.dropdown-menu').first().removeClass('show');
            });
        }

        $('.dropdown-menu a.dropdown-toggle').on('click', function(e) {
          if (!$(this).next().hasClass('show')) {
            $(this).parents('.dropdown-menu').first().find('.show').removeClass("show");
          }
          var $subMenu = $(this).next(".dropdown-menu");
          $subMenu.toggleClass('show');

          $(this).parents('li.nav-item.dropdown.show').on('hidden.bs.dropdown', function(e) {
            $('.dropdown-submenu .show').removeClass("show");
          });

          return false;
        });
    };
})(jQuery);

Answer №1

Upon reviewing this question, I realize it's a bit late but the information may still be useful to others.

The issue is caused by using two containers - either container-fluid or container.

For example:

<div class="container-fluid">
   etc...
</div>

Your navbar will only work until the end of the container and then stop functioning properly.

<main class="container-fluid" role="main">
   etc...
</main>

To avoid this problem, structure your HTML like this:

<div class="container-fluid">
  etc...
    <main role="main">
       etc...
    </main>
</div>

Ensure you only use one container in your website and include all your code within that container.

Answer №2

To potentially resolve the issue, consider changing navbar-fixed-top to fixed-top.

<nav class="navbar navbar-expand-lg navigation  fixed-top">
  <div class="container">
    ....
  </div>
</nav>

It is advisable to steer clear of using margin-left and margin-right as they are not included in border-sizing and can lead to design issues. Instead, opt for padding whenever possible. However, using margin-top and margin-bottom should generally not pose a problem in responsive design.

If hover effects are not functioning properly when resizing the browser window, you may want to try the following CSS solution:

/* submenu open on hover, add css animation if you like */
@media (min-width: 768px)  {
  nav.navigation ul > li:hover > .dropdown-menu  {
    display: block;
  }
  nav.navigation ul > li:not(:hover) > .dropdown-menu  {
    display: none;
  }
}

Answer №3

Yes! Success!

I managed to tackle the issue using a unique method.

Due to having a header above the navbar on my website, I couldn't employ position: fixed, as it would cause the navbar to overlap the header when the page is visited and with top:0.

The Solution :

I calculated the height at which Bootstrap's sticky-top feature worked, and just before that point (from the top), I implemented a media query that changed position: sticky to position: fixed, bringing the navbar to the top as intended.

This approach was effective since the header section is no longer in the way.

I recognize this is more of a temporary solution, but it does the job flawlessly :)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How about exploring a basic example of a button click with the combination of Ajax and Node

Exploring the realms of Ajax and Node.js + Express for the first time, I am currently on a quest to establish communication between the front and back end using buttons. There's a button on an HTML page that I wish to utilize to invoke a function fro ...

Ways to verify whether any of the variables exceed 0

Is there a more concise way in Typescript to check if any of the variables are greater than 0? How can I refactor the code below for elegance and brevity? checkIfNonZero():boolean{ const a=0; const b=1; const c=0; const d=0; // Instead of ma ...

When working with MSAL version 0.1.3 in angularJS, it appears that there is an issue as the Msal.IdToken

Currently, I am utilizing this approach to decode the token and retrieve its expiration date. Here is the code snippet: var decode = Msal.IdToken(localStorage["msal.idtoken"]); This method is chosen to prevent the need for adding an additional jwtdecode ...

The bond between TypeORM and express

I am working on establishing Many-to-One and One-to-Many relationships using TypeORM and MySQL with Express. The database consists of two tables: post and user. Each user can have multiple posts, while each post belongs to only one user. I want to utilize ...

Saving the AJAX response object in a global variable - Important fields are not being retrieved

Currently, I am developing an asynchronous webpage in Grails wherein I invoke a controller and display the response as a D3.js network. To ensure further usability, I saved the object as a global variable. Despite the successful execution of the function u ...

Creating a dynamic number animation and generating content with Vue.js and SCSS

While exploring different methods for creating a number scrolling animation, I stumbled upon the following code snippet (written in SCSS and Vue): new Vue({ el: ".app", data: { number: 0 }, methods: { setNumber(e) { this.n ...

What is the method for adjusting the success button's color using SASS?

My current theme's success button is green, but I want to change it to yellow. How can I achieve this? In the _variables.scss file, the following lines are present: $btn-success-color: $btn-default-color !default; $btn-success-bg: ...

JavaScript Array Creation Guide

Is there a way to generate an array with a length of 3, where each element has the value of 0? If I want the array to look like this: a[0]=0; a[1]=0; a[2]=0; I have experimented with new Array(3), which produces an array a[,,,] of length 3, and new ...

Choose the selectize item to always move to the front

Hey there, I'm currently using the selectize plugin to incorporate tags into my website. Everything is working well, except for the issue of the drop-down item being obscured by some of my other divs. I'm looking to have them function more like ...

Combining datatables.js with an asp.net gridview for enhanced functionality

Currently, I am experimenting with integrating datatables.net into my asp.net gridview. All the necessary js and css files have been included. To apply the datatables, I am utilizing the following code: $(document).ready(function(){ $('#myGridvie ...

Is it possible to trigger the "onbeforeunload" event using JavaScript when navigating between views in an AngularJS application?

Currently, I am working on an AngularJs application that consists of two ng-views. One issue that I have encountered is with the 'onbeforeunload' event. While it works fine when navigating away from the page or refreshing it, it does not trigger ...

Tips for positioning a React component above another component

I am currently facing a challenge while working on a table with an expand more option to display additional details for each specific row. I have implemented a slider to facilitate the expansion of the table. Presently, my ExpandToggle component is embedde ...

Error: Attempting to assign a value to property 'x' of an undefined object has resulted in a TypeError

When I tried to create an array of randomly generated circles (stars) in my first code, I encountered a TypeError on this line: stars[i].x = Math.floor(Math.random() * w) Even though stars is defined in the code, the issue persisted. $(document).ready(f ...

Tips for creating a consistent format based on test cases

var years = Math.floor(seconds / (3600*24*365)) seconds -= years*3600*24*365 var days = Math.floor(seconds / (3600*24)) seconds -= days*3600*24 var hrs = Math.floor(seconds / 3600) seconds -= hrs*3600 var minutes = Math.floor(seconds / 60) ...

Develop a descriptive box for a radio button form using jQuery

I am working on creating a form with simple yes/no questions. If the answer is no, no explanation is needed. However, if the answer is yes, I want to insert a new table row and display a textarea for an explanation. To ensure data validation, I am utilizi ...

Node.js and the Eternal Duo: Forever and Forever-Montior

Currently, I am utilizing forever-monitor to launch a basic HTTP Node Server. However, upon executing the JavaScript code that triggers the forever-monitor scripts, they do not run in the background. As a result, when I end the TTY session, the HTTP server ...

Adjust the flex box height to match the dimensions of the image container

Currently, I am in the process of constructing a chat message layout and I am facing a challenge where I need to incorporate an image within a text bubble. The width of the bubble is fixed, but the height should adjust based on the aspect ratio of the imag ...

Avoid displaying the image when encountering a 404 error, but sometimes a broken image may still appear momentarily

Here is the code snippet I'm currently using: <img ng-show="json.user.picture" ng-src="{{json.user.picture}}" ng-error="json.user.picture = false"> When accessing an image from an external website without permission, a 404 error code is return ...

Save the data from the input form into a JSON file

I'm new to using Express and I want to store the input field value in my JSON file. When I try to do this, I get an error message: POST http://localhost:5500/userData 405 (Method Not Allowed). From what I understand, it seems like the server is not su ...

Error: Unspecified process.env property when using dotenv and node.js

I'm encountering an issue with the dotenv package. Here's the structure of my application folder: |_app_folder |_app.js |_password.env |_package.json Even though I have installed dotenv, the process.env variables are always u ...