Bootstrap 4 activate.bs.scrollspy event is not firing
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);
});
@kim gave the right answer, but I also needed to hook to a scroll-end event, which does not seem to exist - so created something simple using a timeout:
// reset scroll watcher ##
clearTimeout( jQuery.data(this, 'scrollTimer'));
jQuery(window).on('activate.bs.scrollspy', function ( e,obj ) {
// console.log(obj.relatedTarget);
jQuery.data( this, 'scrollTimer', setTimeout(function() {
// console.log("Didn't scroll in 1/4 sec..");
// no scroll items are marked as active ##
if ( ! jQuery(".scrollspy-item.active")[0]){
// console.log("Can't fund any active scrollspy items..");
// add class to parent again ##
jQuery(".list-group-item.current").addClass( 'active' );
}
}, 250 ) );
});
In this case, I'm checking if any "scrollspy-items" are marked as active, or not and then adding the active class to a parent item, as we use the scrollspy in place in a sidebar menu.