Scrollspy in Bootstrap 5.2

Hi, I am struggling to get scrollspy to work in BS5.2

I followed the instructions by @PeteSharp for Bootstrap 4 Active Link Class color is not changing - #37 by Malachiman

But on trying to adapt it for BS5 I am not having success.

It’s prob to do with my lack of JS knowledge. Here’s what I’ve added at in the footer:

<script>
window.addEventListener('load', (event) => {
  var scrollarea = document.getElementsByTagName('body')[0];
  scrollarea.setAttribute('data-bs-spy', 'scroll');
  scrollarea.setAttribute('data-bs-target', '.site-navigation');

  var navHeight = document.getElementById('sly-nav').offsetHeight;

  $('body').scrollspy({ target: '.site-navigation', offset:(navHeight) });
});

const scrollSpy = new bootstrap.ScrollSpy(document.body, {
  target: '.site-navigation'
});

</script>

The body attributes get added and even an .active class on the first item, but the .active class does not switch to the next items as I scroll: https://sly-design.co.uk/

Has anyone achieved scrollspy for BS5.2 in Blocs?

1 Like

I would change the code to pure Javascript now.

By the way you added a class called .sly-nav to your nav, but you are looking for it as an ID, to get the height offset, you can see the error in the browser inspector.

1 Like

Yes, I see what you’re saying, but in that case, according to the docs, simply adding only:

<script>
const scrollSpy = new bootstrap.ScrollSpy(document.body, {
  target: '.site-navigation'
});
</script>

to the foot should do it (no body data-attributes needed). But it does not, it only goes so far as adding the .active class to the first item. But on scrolling to new sections does not change the class on other nav items: https://sly-design.co.uk/

Ok, all sorted… just needed to add overflow-x: unset; style to the body, it won’t work without it.

And this is all that’s needed in the footer code:

<script>
const scrollSpy = new bootstrap.ScrollSpy(document.body, {
  target: '.site-navigation'
});
</script>
1 Like

Wow.

Overflow-x: unset;
I’ve been looking for this solution for over a year. How did you figure this out?

Overflow the killer. I think I mentioned this in the BS4 tutorial. And It also kills sticky-top.

I did have some trouble with scrollspy not long ago and apparently there was a recent Bootstrap release that broke it. Looks like it’s fixed now.

Hi @simonclay, what (and how) did you add overflow-x: unset to?

I’m having the same problem. It’s not the first menu item, but the third that is showing the active state no matter where I am on the page! (and sometimes the first) Everything has the correct target URL.


thanks