8

We are using the twitter bootstrap scrollspy on a sidebar ul/il list, this works great. We do however also use smooth scrolling when clicking the links in the sidebar. This causes the scrollspy to highlight each and every element that comes into view, as it should in normal cases.

But when the scrolling is triggered by a click on the links in the side nav, the users most likely don't expect the menu to animate as the scrolling occurs. Is there any way to temporarily disable the scrollspy while the animated scroll is running, and then reenable it once scrolling is complete?

Anshad Vattapoyil
  • 23,145
  • 18
  • 84
  • 132
Roger Johansson
  • 22,764
  • 18
  • 97
  • 193

2 Answers2

8

By setting a class as the target of scrollspy you can dynamically stop/resume scrollspy operation.

$('body').scrollspy({ target: '.spy-active' });

Now one will just need to add or remove the .spy-active class on the navigation.

JofryHS
  • 5,804
  • 2
  • 32
  • 39
  • The issue is when reactivating (readding the class), scrollSpy does not refresh the current active class. – dude May 27 '16 at 17:19
  • @dude, you can re-enable the class by doing something with your `.animate`'s event in the `complete` callback with something like: `complete: function() { $("#nav").addClass("active-spy"); $(event.target.parentNode).addClass("active"); }`. Here's a fiddle: https://jsfiddle.net/o92wrpg8/2/ – Max Starkenburg Jun 29 '16 at 14:40
0

add the following to the top of your local javascript...

$.fn.scrollspy.Constructor.prototype.destroy = function(){
    this.$element.off('scroll.bs.scroll-spy.data-api');
    this.$body.removeData('bs.scrollspy');
    return this.$body;
}
dkimbell13
  • 123
  • 7
  • Could you explain how this works, and in particular how unhooking only the `scroll.bs.scroll-spy.data-api` event (which I have never heard of) automagically unhooks all the other scrollspy events too? – Szczepan Hołyszewski Sep 28 '17 at 10:57
  • By perusing the actual ScrollSpy plugin code at **[link](https://gist.github.com/kirov/9482666)** You can see that there is only one event attached to the scrollspy element. the 'scroll.bs.scroll-spy.data-api' event. – dkimbell13 Jan 24 '18 at 16:53