Skip to content

Instantly share code, notes, and snippets.

@siamkreative
Last active January 9, 2017 06:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save siamkreative/2b431d0759a9b568cc9c850d1b3bd73c to your computer and use it in GitHub Desktop.
Save siamkreative/2b431d0759a9b568cc9c850d1b3bd73c to your computer and use it in GitHub Desktop.
Boostrap 4 Navbar Fixed to top. Placement using JavaScript

What Is This?

This is for the fixed to top version of the Boostrap 4 navbar. Instead of setting the padding and top position in CSS, let's use JavaScript to get it dynamically.

How To Use?

It is best to use the pure JavaScript version. It will be executed earlier since it does not require jQuery to be loaded. The vanilla JavaScript version can be used in the <head> section.

If you are a performance concerned developer, your scripts are probably in the footer just before </body>. Therefore, there might be a slight delay before the jQuery snippet is executed. This can lead to elements jumping around...

For perfectly smooth transition, it is best to execute this JavaScript as soon as the DOM is rendered.

$(function () {
// Adjusting spacing for fixed Navbar
// http://caniuse.com/#search=DOMContentLoaded
var body = $('body');
var navbar = $('.navbar');
var navbarHeight = navbar[0].getBoundingClientRect().height;
var categoryNav = $('.category-nav');
var categoryNavHeight = categoryNav[0].getBoundingClientRect().height;
body.css('padding-top', navbarHeight + categoryNavHeight);
categoryNav.css('top', navbarHeight);
});
// Adjusting spacing for fixed Navbar
document.addEventListener('DOMContentLoaded', function (event) {
var navbar = document.querySelectorAll('.navbar')[0];
var navbarHeight = navbar.getBoundingClientRect().height;
var categoryNav = document.querySelectorAll('.category-nav')[0];
var categoryNavHeight = categoryNav.getBoundingClientRect().height;
document.body.style.paddingTop = navbarHeight + categoryNavHeight + 'px';
categoryNav.style.top = navbarHeight + 'px';
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment