Search code examples
bootstrap-4scrollspy

Scrollspy issues with Bootstrap4 and list-group collapsible


I updated my application to use Boostrap 4.1, and now I get a weird behaviour when using ScrollSpy. I am trying to create a collapsible menu, and I'm using the list-group/list-group-item. For some reason though, when scrolling down from the first item to the second, the scroll goes to the main anchor (to the Main Menu), instead of staying on the first item (until it reaches the second).

I'm sorry if my explanation of the problem is not that accurate, but I'm confident that this fiddle will help better understand it:

http://jsfiddle.net/aq9Laaew/189549/

This is the menu:

<nav class="list-group fixedMenu" id="list-example">
      <a href="#menuSpy" data-toggle="collapse" class="list-group-item" aria-expanded="true">
          <span>Main Menu</span>
      </a>
      <ul class="sub collapse show" id="menuSpy">
          <a class="list-group-item list-group-item-action" href="#list-item-1">Item 1</a>
          <a class="list-group-item list-group-item-action" href="#list-item-2">Item2</a>
          <a class="list-group-item list-group-item-action" href="#list-item-3">Item 3</a>
          <a class="list-group-item list-group-item-action" href="#list-item-4">Item 4</a>
      </ul>
</nav>

And this is the content:

<div data-spy="scroll" data-target="#list-example" data-offset="0" class="scrollspy-example">
    <h4 id="list-item-1">Item 1</h4>
    <p>...</p>
    <h4 id="list-item-2">Item 2</h4>
    <p>...</p>
    <h4 id="list-item-3">Item 3</h4>
    <p>...</p>
    <h4 id="list-item-4">Item 4</h4>
    <p>...</p>
</div>

Any help is appreciated!

Thank you in advance.


Solution

  • The scrollspy target menu should be #menuSpy. Otherwise it will target the first link in list-example when it scrolls.

    $('body').scrollspy({
        target: '#menuSpy'
    });
    

    http://jsfiddle.net/o7tf53ce/

    Updated with multiple menus: https://www.codeply.com/go/aMpKp07E0t