• US: +1 347 223 5853   UK: +44 20 8 1234 790
  • Live Chat

Navbar – Bootstrap 4 – sticky Navbar

  •  admin
  •  Nov 24, 2018

In the latest version of Bootstrap, Bootstrap 4 Beta, affix is not supported any longer. If you were used to making your navbar “fixed after scrolling” and integrated affix in your design before, you’ll have to find another solution. There is a nice example on Codepen that shows us with CSS, HTML for the navbar and a javascript how to do this.

Building the navbar

Find here the complete code.

The HTML

<nav class="navbar navbar-expand-lg navbar-light top-navbar" data-toggle="sticky-onscroll"><nav>
Only the data-toggle is new. Do the rest as you are used to.

The CSS


.sticky.is-sticky {
position: fixed;
left: 0;
right: 0;
top: 0;
z-index: 1000;
width: 100%;
}

The JAVASCRIPT


// Sticky navbar
// =========================
$(document).ready(function () {
// Custom function which toggles between sticky class (is-sticky)
var stickyToggle = function (sticky, stickyWrapper, scrollElement) {
var stickyHeight = sticky.outerHeight();
var stickyTop = stickyWrapper.offset().top;
if (scrollElement.scrollTop() >= stickyTop) {
stickyWrapper.height(stickyHeight);
sticky.addClass("is-sticky");
}
else {
sticky.removeClass("is-sticky");
stickyWrapper.height('auto');
}
};

// Find all data-toggle="sticky-onscroll" elements
$('[data-toggle="sticky-onscroll"]').each(function () {
var sticky = $(this);
// insert hidden element to maintain actual top offset on page
var stickyWrapper = $('<div>').addClass('sticky-wrapper');
sticky.before(stickyWrapper);
sticky.addClass('sticky');

// Scroll & resize events
$(window).on('scroll.sticky-onscroll resize.sticky-onscroll', function () {
stickyToggle(sticky, stickyWrapper, $(this));
});

// On page load
stickyToggle(sticky, stickyWrapper, $(window));
});
});

admin

Other posts by

Us data center. Kvm vps hosting.