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?
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');
});
};
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