I am working on a website in Bootstrap 4, that has sections with light and dark backgrounds and a fixed navbar.
The navbar is dark (has the css class bg-dark>
I'm thinking i'd be easier to properly exploit Bootstrap scrollspy's "activate.bs.scrollspy" event rather than "breaking its rules" and simply override the default href navigation with javascript code.
So i'd suggest you add back the id's to the divs and the matching framgment hrefs to the anchors, let Bootstrap give you the target in the "activate.bs.scrollspy" event via the obj.relatedTarget property, toggle the classes as needed and optionally remove the "activated" class from the nav items so it doesn't appear like the sections are related. If you have additional sections, try using hidden anchors or a hidden nav altogether.
Of course, the cleanest way would be in my opinion to ditch the scrollspy and use window.scrollY and $(window).on('scroll', ...).
Check out the snippet:
$(window).on('activate.bs.scrollspy', function (e, obj) {
if ((window.innerHeight + window.pageYOffset) >= document.body.offsetHeight) {
return;
}
var isBGLight = $(obj.relatedTarget).hasClass('bg-light');
$('.navbar').toggleClass('navbar-dark bg-dark', isBGLight)
.toggleClass('navbar-light bg-light', !isBGLight);
//Optional: Remove the active class from the anchor so it doesn't look like the nav is linked to the sections
$('.navbar-nav a[href="' + obj.relatedTarget + '"]').removeClass('active');
});
//Here we do the actual navigation
$('.navbar-nav a').click(function(e) {
//Prevent anchor's default behaviour of briefly jumping to the given section before navigating to another page
e.preventDefault();
//Substring to eliminate the leading "#"
window.location.href = $(e.target).attr('href').substring(1) + '.html';
})
.page-section {
padding: 70px 10px
}
.page-section.bg-dark * {
color: #fff;
}
Section 1
Try to scroll this section and look at the navigation bar while scrolling! Try to scroll this section and look at the navigation bar while scrolling!
Try to scroll this section and look at the navigation bar while scrolling! Try to scroll this section and look at the navigation bar while scrolling!
Section 2
Try to scroll this section and look at the navigation bar while scrolling! Try to scroll this section and look at the navigation bar while scrolling!
Try to scroll this section and look at the navigation bar while scrolling! Try to scroll this section and look at the navigation bar while scrolling!
Section 3
Try to scroll this section and look at the navigation bar while scrolling! Try to scroll this section and look at the navigation bar while scrolling!
Try to scroll this section and look at the navigation bar while scrolling! Try to scroll this section and look at the navigation bar while scrolling!