Bootstrap 4 activate.bs.scrollspy event is not fir

2019-04-10 08:52发布

问题:

I'm using Bootstrap v4.0.0

I have included the necessary JavaScript files (jQuery, popper and Bootstrap) and the necessary CSS files as well.

This is the HTML:

<body data-spy="scroll" data-target="#my-navbar-collapse" data-offset="100">
    <!-- ... -->
    <div class="collapse navbar-collapse" id="my-navbar-collapse">
        <ul class="nav navbar-nav" role="tablist">
            <li class="nav-item">
                <a class="nav-link" href="#one">One</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="#two">Two</a>
            </li>
        </ul>
    </div>
    <!-- ... -->
    <section id="one">
        Content.
    </section>
    <!-- ... -->
    <section id="two">
        More content.
    </section>
    <!-- ... -->
    <script>
        $(function() {
            // As per the official docs: 
            // https://getbootstrap.com/docs/4.0/components/scrollspy/#events
            $('[data-spy="scroll"]').on('activate.bs.scrollspy', function() {
                console.log("This event is not firing...");
            });
        });
    </script>
</body>

The menu items get highlighted properly when scrolling, but the JavaScript event activate.bs.scrollspy is not firing.

I also tried to hook the event to the navbar itself, but it does not fire either:

$('#my-navbar-collapse').on('activate.bs.scrollspy', function () {
    console.log("Not firing either...");
})

I used to use this code with Bootstrap 3 and worked just fine.

Any thoughts?

Thank you.

回答1:

For some reason explained here, when you use body for the spy element the event gets activated on the window.

        $(window).on('activate.bs.scrollspy', function () {
            console.log("This event is not firing...");
        });

Demo: https://www.codeply.com/go/aN4tfy0zU0

EDIT

The target element can be obtained in the 2nd event param:

      $(window).on('activate.bs.scrollspy', function (e,obj) {
          console.log(obj.relatedTarget);
      });