Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot properly refresh Bootstrap scrollspy spying on <body> element

I've been referencing this post regarding Bootstrap's scrollspy component. In my code, I instantiate a new scrollspy to spy on the body element using:

$("body").scrollspy({ offset: 25 });

Later on in my code, I make an AJAX call and add/remove elements from the page. This causes the scrollspy to be misaligned, so I need to refresh the scrollspy. I have tried performing this refresh operation many ways, such as:

$("body").scrollspy("refresh");

and

$('[data-spy="scroll"]').each(function () {
  $(this).scrollspy('refresh');
}); 

However, neither of these code snippets bring about any change in the behavior of the scrollspy. I believe this is because the scrollspy is spying directly on the body element, but I am unsure of how to have the scrollspy refresh following my AJAX calls. Does anyone know how I might refresh my scrollspy?

like image 686
PaulDapolito Avatar asked Aug 12 '14 13:08

PaulDapolito


1 Answers

It appears that it is not possible to refresh a scrollspy that is set to spy on the body element via a call to $("body").scrollspy(). In order to use the refresh functionality documented on the Bootstrap website, I had to explicitly declare the data-spy and data-target attributes of the body tag (where scrollingNav is the id of the nav bar in which to visualize the scrolling):

<body data-spy="scroll" data-target="#scrollingNav">

Then, to refresh this scrollspy when elements were dynamically added/removed from the page, I used the following method:

function refreshScrollSpy() {
    $('[data-spy="scroll"]').each(function () {
        $(this).scrollspy('refresh');
    }); 
};
like image 96
PaulDapolito Avatar answered Oct 07 '22 04:10

PaulDapolito