Scrollspy is a jQuery plugin that tracks certain elements and which element the user's screen is currently centered on. Our main demo of this is our table of contents on every documentation page to the right. Clicking on these links will also scroll the page to that element.
<div class="row">
<div class="col s12 m9 l10">
<div id="introduction" class="section scrollspy">
<p>Content </p>
</div>
<div id="structure" class="section scrollspy">
<p>Content </p>
</div>
<div id="initialization" class="section scrollspy">
<p>Content </p>
</div>
</div>
<div class="col hide-on-small-only m3 l2">
<ul class="section table-of-contents">
<li><a href="#introduction">Introduction</a></li>
<li><a href="#structure">Structure</a></li>
<li><a href="#initialization">Initialization</a></li>
</ul>
</div>
</div>
Initialization
document.addEventListener('DOMContentLoaded', function() {
var elems = document.querySelectorAll('.scrollspy');
var instances = M.ScrollSpy.init(elems, {
// specify options here
});
});
// Or with jQuery
$(document).ready(function(){
$('.scrollspy').scrollSpy({
// specify options here
});
});
Options
Name | Type | Default | Description |
---|---|---|---|
throttle | Number | 100 | Throttle of scroll handler. |
scrollOffset | Number | 200 | Offset for centering element when scrolled to. |
activeClass | String | 'active' | Class applied to active elements. |
getActiveElement | Function | Used to find active element. | |
onEnter | Function | null | Callback function called on section enter. |
onExit | Function | null | Callback function called on section exit. |
getActiveElement
This is the default function used for finding the active element where id is the id of the scrollspy element. It returns a CSS selector of the element you want marked active.
function(id) {
return 'a[href="#' + id + '"]';
}
onEnter and onExit
These functions will also receive the active section's element as the first parameter and the active section's link in the table of contents as the second parameter.
function(el, trigger) {
console.log(el, trigger);
}
Methods
Because jQuery is no longer a dependency, all the methods are called on the plugin instance. You can get the plugin instance like this:
var instance = M.ScrollSpy.getInstance(elem); /* jQuery Method Calls You can still use the old jQuery plugin method calls. But you won't be able to access instance properties. $('.scrollspy').scrollSpy('methodName'); */
.destroy();
Destroy plugin instance and teardown
instance.destroy();
Properties
Name | Type | Description |
---|---|---|
el | Element | The DOM element the plugin was initialized with. |
options | Object | The options the instance was initialized with. |