I am trying to capture the event of Scrollspy in order to run a function. Scrollspy is working to change the activate link on the navbar. But I am unable to capture the event to use it elsewhere.
This is a snippet of the code:
<body data-spy="scroll" data-target="#navbar" data-offset="30">
<script>
$(document).ready(function(){
$('body').scrollspy({target: "#navbar", offset: 30});
});
$(document).ready(function(){
$('#navbar').on('activate.bs.scrollspy', function() {
console.log('sparkle, sparkle');
});
});
</script>
I understand that in some versions of Bootstrap capturing the event is not possible/working?
Please advise.
Actually this is one of the very few things in Bootstrap 4 that are not well documented –or buggy–. As you have already read at the Events section of the Scrollspy documentation, the activate.bs.scrollspy event should be fired on the scroll element –the one with data-spy="scroll"–, and handled accordingly:
$('[data-spy="scroll"]').on('activate.bs.scrollspy', function(event) {
console.log('activate.bs.scrollspy', event);
})
However, it is not documented, that when the Scrollspy is used on the <body> element, the activate.bs.scrollspy event will be available only on the window object.
So, you can catch this Scrollspy event like so:
$(window).on('activate.bs.scrollspy', function (event) {
console.log('activate.bs.scrollspy', event);
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With