Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

change active menu item on page scroll javascript

// Cache selectors
var topMenu = $("#top-menu"),
    topMenuHeight = topMenu.outerHeight()+15,
    // All list items
    menuItems = topMenu.find("a"),
    // Anchors corresponding to menu items
    scrollItems = menuItems.map(function(){
      var item = $($(this).attr("href"));
      if (item.length) { return item; }
    });

// Bind to scroll
$(window).scroll(function(){
   // Get container scroll position
   var fromTop = $(this).scrollTop()+topMenuHeight;

   // Get id of current scroll item
   var cur = scrollItems.map(function(){
     if ($(this).offset().top < fromTop)
       return this;
   });
   // Get the id of the current element
   cur = cur[cur.length-1];
   var id = cur && cur.length ? cur[0].id : "";
   // Set/remove active class
   menuItems
     .parent().removeClass("active")
     .end().filter("[href='#"+id+"']").parent().addClass("active");
});​
Comment

PREVIOUS NEXT
Code Example
Javascript :: event on trible click in js 
Javascript :: initializing a property asynchronously 
Javascript :: getters and setters in java script 
Javascript :: push code from vscode using CL 
Javascript :: how to signup users without login in firebase js 
Javascript :: Javascript multiplier function 
Javascript :: object.keys map 
Javascript :: hide show jquery 
Javascript :: javascript find the smallest and biggest number in array 
Javascript :: generate history logs 
Javascript :: How to create a debounce higher order function 
Javascript :: show more vs editor shortcut key 
Javascript :: javascript pure ajax promise 
Javascript :: javascript set default button form 
Javascript :: shorten req.body. function 
Javascript :: how to change in website with node js 
Javascript :: what is fn extend 
Javascript :: JS equal sibling btns height 
Javascript :: How can I use a regex variable in a query for MongoDB 
Javascript :: js array map and update tat array value 
Javascript :: math.factorial javascript 
Javascript :: Ghost-Blog MySQL install was not found 
Javascript :: pause media stream javascript 
Javascript :: _.clone underscore 
Javascript :: Prototype Constructor Will Be Class or Function 
Javascript :: json to css converter 
Javascript :: how to style on-click in react/ vuejs router 
Javascript :: angularjs $q all hash 
Javascript :: dropdown list trigger change with value jquery 
Javascript :: javascript enum includes value 
ADD CONTENT
Topic
Content
Source link
Name
6+3 =