Advertisement
Guest User

Untitled

a guest
Jun 25th, 2017
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.99 KB | None | 0 0
  1. // Highlight current page menu item as user scrolls
  2. var lastId,
  3. pageMenu = $("nav"),
  4. pageMenuHeight = pageMenu.outerHeight(),
  5. // All list items
  6. menuItems = pageMenu.find("a"),
  7. // Anchors corresponding to menu items
  8. scrollItems = menuItems.map(function(){
  9. var item = $($(this).attr("href"));
  10. if (item.length) { return item; }
  11. });
  12.  
  13. // Bind to scroll
  14. $(window).scroll(function(){
  15. // Get container scroll position
  16. var fromTop = $(this).scrollTop()+pageMenuHeight;
  17.  
  18. // Get id of current scroll item
  19. var cur = scrollItems.map(function(){
  20. if ($(this).offset().top < fromTop)
  21. return this;
  22. });
  23. // Get the id of the current element
  24. cur = cur[cur.length-1];
  25. var id = cur && cur.length ? cur[0].id : "";
  26.  
  27. if (lastId !== id) {
  28. lastId = id;
  29. // Set/remove active class
  30. menuItems
  31. .parent().removeClass("active")
  32. .end().filter("[href=\\#"+id+"]").parent().addClass("active");
  33. }
  34. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement