Highlight Active Menu Item Based On Scroll Position - ScrollSpy
File Size: | 4.97 KB |
---|---|
Views Total: | 12444 |
Last Update: | |
Publish Date: | |
Official Website: | Go to website |
License: | MIT |

A super tiny (less than 1kb) jQuery scrollspy plugin to highlight active menu items in the navigation based on the scroll position of the corresponding content within a container or the whole document.
How to use it:
1. Create a navigation containing anchor links as follows:
<div class="menu-wrapper"> <ul class="menu"> <li><a href="#start">Start</a></li> <li><a href="#middle">Middle</a></li> <li><a href="#end">End</a></li> </ul> </div>
2. Create content sections for the anchor links.
<div class="content"> <section id="start"> <p>start</p> </section> <section id="middle"> <p>middle</p> </section> <section id="end"> <p>end</p> </section> </div>
3. Load the JavaScript jquery.scroll-spy.js
after jQuery.
<script src="/path/to/cdn/jquery.min.js"></script> <script src="/path/to/dist/jquery.scroll-spy.min.js"></script>
4. Call the function scrollSpy
on the parent container and determine the selector of the target anchor links.
$('.content-wrapper').scrollSpy({ target: $('.menu a') }).scroll();
5. Apply your own CSS styles to the active menu item.
.active { background-color: blue; color: red; transition: .5s ease-out; }
6. Override the default active class.
$('.content-wrapper').scrollSpy({ target: $('.menu a'), activeClass: 'active' }).scroll();
7. Determine whether to fix the navigation to the top of the page/container. Default: true.
$('.content-wrapper').scrollSpy({ target: $('.menu a'), fixed: true }).scroll();
This awesome jQuery plugin is developed by twg-group. For more Advanced Usages, please check the demo page or visit the official website.