Is there a way I can add scrollspy to Bricks builder for a one-page website with the html anchors at the top so that the active element changes as the user scrolls through the sections?
Thanks!
Nevermind, I found a solution! This JS in custom page code does the trick.
<script>
document.addEventListener('DOMContentLoaded', () => {
const sections = document.querySelectorAll('section[id]');
const navLinks = document.querySelectorAll('.navbar a[href^="#"]');
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
const id = entry.target.id;
const link = document.querySelector(`.navbar a[href="#${id}"]`);
if (!link) return;
if (entry.isIntersecting) {
link.classList.add('navbar_active');
} else {
link.classList.remove('navbar_active');
}
});
}, {
rootMargin: '-25% 0px -75% 0px' // Adjust when the active state should trigger
});
sections.forEach(sec => observer.observe(sec));
// Optional: Instantly update active class when a nav link is clicked
navLinks.forEach(link => {
link.addEventListener('click', () => {
navLinks.forEach(l => l.classList.remove('navbar_active'));
link.classList.add('navbar_active');
});
});
});
</script>
You just need to rename each section’s ID so that it matches the HTML anchor you’re using for it (e.g. ‘About’ in the navbar links to example.com#about, and the ID for the about section is 'about)
Then just style the active link using custom CSS for the .navbar_active
class.
Now when each section enters the viewport the active element in the navbar will update. For extra points add transition CSS to make it nice and smooth!