Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Twitter Bootstrap ScrollSpy to execute a function

I would like to load more data after ScrollSpy receives notification. But I don't see how to capture that event and execute a function.

like image 742
opengrid Avatar asked Feb 18 '12 18:02

opengrid


People also ask

How does Bootstrap Scrollspy work?

Scrollspy works according to the scroll position or the position at which the user is currently is seeing. Bootstrap scrollspy targets the navigation bar contents automatically on scrolling the area.

How do you use scroll spy?

Add data-spy="scroll" to the element that should be used as the scrollable area (often this is the <body> element). Then add the data-target attribute with a value of the id or the class name of the navigation bar ( . navbar ). This is to make sure that the navbar is connected with the scrollable area.

How do I scroll using Bootstrap?

To easily add scrollspy behavior to your topbar navigation, add data-bs-spy="scroll" to the element you want to spy on (most typically this would be the <body> ). Then add the data-bs-target attribute with the ID or class of the parent element of any Bootstrap .


3 Answers

UPDATED This trigger has been pushed into the main build now. You can see it in full docs. http://twitter.github.com/bootstrap/javascript.html#scrollspy

There is an update in the working branch on github that fires an activate callback.

References

  • https://github.com/twitter/bootstrap/issues/2482

Once you grab the activate trigger, you can call it like so:

$("#nav li").on('activate', function() {
   //do stuff
});
like image 123
Merk Maloney Avatar answered Oct 06 '22 22:10

Merk Maloney


This is for Bootstrap 4 (beta 3):
In general, the usage of the Scrollspy event did not change from Bootstrap 3. As it is stated at the Events section of the Scrollspy documentation, the activate.bs.scrollspy event will be fired on the scroll element –the one with data-spy="scroll"– whenever a new item becomes activated by the Scrollspy. You can listen to it like that:

$('[data-spy="scroll"]').on('activate.bs.scrollspy', function(event) {
    console.log('activate.bs.scrollspy', event);
})

But!
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, in this rather common case, you can catch the Scrollspy event like so:

$(window).on('activate.bs.scrollspy', function (event) {
    console.log('activate.bs.scrollspy', event);
})
like image 4
dferenc Avatar answered Oct 06 '22 21:10

dferenc


For bootstrap 3 you can do it like this (docs)

$('#myScrollspy').on('activate.bs.scrollspy', function () {
  // do something…
})
like image 1
alex Avatar answered Oct 06 '22 20:10

alex