Bootstrap 4 fixed navbar that hides until page scrolled up

johna 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).

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

Web Development Retro Computing

Converting dBase IV programs to run in the browser

by johna | September 13, 2024
Some pointless entertainment trying to get some old dBase programs running in the browser.

Web Development

How to set up a debugging using the Turnkey Linux LAMP stack and VS Code

by johna | December 19, 2023
The second part in my guide to setting up a website and database using the Turnkey Linux LAMP stack.

Website Hosting Web Development

How to set up a website and database using the Turnkey Linux LAMP stack

by johna | November 18, 2023
If you need to host your own website for the purposes of web development, Turnkey Linux LAMP Stack is an easy to install all-in-one solution that you can set up on a spare computer or a VM (Virtual Machine).

Comments

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

Leave a Comment

About

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

I recommend ASPnix for web hosting and Crazy Domains for domain registration.

Subscribe

Get the latest posts delivered to your inbox.