Created
August 5, 2015 20:45
-
-
Save jaredatch/44b68b2b79e3ab9f8817 to your computer and use it in GitHub Desktop.
Simple jQuery scrollspy
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| (function ($) { | |
| /** | |
| * Scroll spy | |
| */ | |
| // Cache selectors | |
| var lastId, | |
| scrollSpyMenu = $(".process-nav"); | |
| scrollSpyMenuHeight = scrollSpyMenu.outerHeight()+55; | |
| scrollSpyMenuItems = scrollSpyMenu.find('a'); | |
| scrollItems = scrollSpyMenuItems.map(function(){ | |
| var item = $($(this).attr('href')); | |
| if (item.length) { | |
| return item; | |
| } | |
| }); | |
| // Bind to scroll | |
| $(window).scroll(function(){ | |
| var fromTop = $(this).scrollTop()+scrollSpyMenuHeight; | |
| var cur = scrollItems.map(function(){ | |
| if ($(this).offset().top < fromTop) | |
| return this; | |
| }); | |
| cur = cur[cur.length-1]; | |
| var id = cur && cur.length ? cur[0].id : ""; | |
| if (lastId !== id) { | |
| lastId = id; | |
| scrollSpyMenuItems.removeClass('active').filter("[href=#"+id+"]").addClass("active"); | |
| } | |
| }); | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment