Advertisement
Guest User

Untitled

a guest
Sep 21st, 2017
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.90 KB | None | 0 0
  1. var lastId,
  2. topMenu = $(".menu"),
  3. topMenuHeight = topMenu.outerHeight()+15,
  4. // All list items
  5. menuItems = topMenu.find("a"),
  6. // Anchors corresponding to menu items
  7. scrollItems = menuItems.map(function(){
  8. var item = $($(this).attr("href"));
  9. if (item.length) { return item; }
  10. });
  11.  
  12.  
  13. // Bind to scroll
  14. $(window).scroll(function(){
  15. // Get container scroll position
  16. var fromTop = $(this).scrollTop()+topMenuHeight;
  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. .removeClass("active").filter("[href='#"+id+"']").addClass("active");
  32. }
  33. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement