Bootstrap 4 fixed navbar that hides until page scrolled up

John Avis by | March 8, 2018 | Bootstrap Web Development

Fixed navbars – that stay at the top of the screen at all times – are common and useful, but sometimes annoying as they can block the top part of the page (sometimes obscuring page anchors).
Fixed navbars – that stay at the top of the screen at all times – are common and useful, but sometimes annoying as they can block the top part of the page (sometimes obscuring page anchors).

I like the functionality that I have seen on some websites where the navbar will scroll away as you move down the page, but re-appears as soon as you start scrolling up the page.

To add this functionality to Bootstrap 4 I made the following changes to the Bootstrap 4 navbar.

CSS:

.navbar-outer {
position: relative;
height: 56px;
}
.absolute-top {
position: absolute;
top: 0;
right: 0;
left: 0;
z-index: 1030
}


jQuery (note two references to the navbar by id, in this example “navbar1”):

$(function () {
var lastPos = $(this).scrollTop();

setInterval(function () {
var thisPos = $(this).scrollTop();
if ($(this).scrollTop() > 1 && thisPos < (lastPos - 2)) {
$("#navbar1").removeClass("absolute-top").addClass("fixed-top");
} else {
if ($(this).scrollTop() <= 1 || thisPos > (lastPos + 2)) {
$("#navbar1").removeClass("fixed-top").addClass("absolute-top");
}
}
lastPos = thisPos;
}, 100);
});


For the HTML markup, several changes are required.

1) Add a div around the Bootstrap 4 navbar:

<div class="navbar-outer">
…navbar code here…
</div>


2) Give the navbar an id, the same as used in the jQuery code (“navbar1” in the sample).

3) Add the class “absolute-top” to the navbar, eg:

<div class="navbar-outer">
<nav id="navbar1" class="navbar navbar-expand-lg navbar-light bg-light absolute-top">
…navbar code here…


Please see the sample below for a demonstration of this.

Demo

Related Posts

Bootstrap

Bootstrap Icons in Alpha

by John Avis | December 9, 2019

The Bootstrap team have introduced their own open-source icon set.


Bootstrap

What's new in Bootstrap 4.4.0 and 4.4.1?

by John Avis | November 27, 2019

Read about the two major improvements in Bootstrap 4.4.0, released 26 November 2019.


Computers & Internet Web Development Website Hosting

500 Internal Server Error after migrating from IIS 7.5 to IIS 10

by John Avis | November 4, 2019

As support ends for Microsoft Windows Server 2008 I have recently gone through migrating some websites to a new server running Windows Server 2016 and IIS 10 but some of the websites did not work.

Comments

There are no comments yet. Be the first to leave a comment!

Leave a Comment

Tags

About me

...random postings about web development and programming, Internet, computers, electronics and automotive topics.

Subscribe

Get the latest posts delivered to your inbox.