EduardET

Highlight Menu Item when section is in viewport

Jun 21st, 2018
176
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <script>
  2. ( function( $ ) {
  3.     $( document ).ready( function() {
  4.         var homepageLinks = $( '#menu-main-menu-desktoptablet .homepage-item' ),
  5.             lastId,
  6.             topMenu = $( '#menu-main-menu-desktoptablet' ),
  7.             topMenuHeight = topMenu.outerHeight() + 1,
  8.             menuItems = topMenu.find( '.homepage-item a' ),
  9.             scrollItems = menuItems.map( function() {
  10.                 var item = $($( this ).attr( 'href' ));
  11.                 if ( item.length ) { return item; }
  12.             } );
  13.  
  14.         console.log(scrollItems );
  15.  
  16.         if ( $( 'body' ).hasClass( 'home' ) ) {
  17.             homepageLinks.each( function() {
  18.                 var link = $( this ).find( 'a' );
  19.                 $( this ).removeClass( 'current-menu-item' );
  20.                 $( '#menu-main-menu-desktoptablet .home-item' ).addClass( 'current-menu-item' );
  21.                 link.click( function() {
  22.                     homepageLinks.removeClass( 'current-menu-item' );
  23.                     $( this ).parent().addClass( 'current-menu-item' );
  24.                 } )
  25.             } );
  26.  
  27.             // Bind to scroll
  28.             $( window ).scroll( function() {
  29.                 // Get container scroll position
  30.                 var fromTop = $( this ).scrollTop() + topMenuHeight;
  31.  
  32.                 // Get id of current scroll item
  33.                 var cur = scrollItems.map( function() {
  34.                     if ( $( this ).offset().top < fromTop )
  35.                         return this;
  36.                 } );
  37.  
  38.                 // Get the id of the current element
  39.                 cur = cur[ cur.length - 1 ];
  40.                 var id = cur && cur.length ? cur[ 0 ].id : '';
  41.  
  42.                 if ( lastId !== id ) {
  43.                     lastId = id;
  44.                     // Set/remove active class
  45.                     menuItems
  46.                         .parent().removeClass( 'current-menu-item' )
  47.                         .end().filter( '[href="#' + id + '"]' ).parent().addClass( 'current-menu-item' );
  48.                 }
  49.             } );
  50.         }
  51.     } );
  52. } )( jQuery );
  53. </script>
Advertisement
Add Comment
Please, Sign In to add comment