Last active
March 29, 2022 10:38
-
-
Save Garconis/a6ef4da6763f59316f2ec1094ca2a919 to your computer and use it in GitHub Desktop.
WordPress | Highlight Nav Menu Item if ID is in Viewport
This file contains 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($) { | |
// set the variables and ideal viewport height | |
$.fn.isInViewport = function() { | |
var elementTop = $(this).offset().top; | |
var elementBottom = elementTop + $(this).outerHeight(); | |
// viewport top starts at bottom of header height | |
var viewportTop = $(window).scrollTop() + 79; | |
// viewport bottom is the window height minus the header height (79) and sticky footer height (92) | |
var viewportBottom = ( viewportTop + $(window).height() ) - 171; | |
return elementBottom > viewportTop && elementTop < viewportBottom; | |
}; | |
$(window).on('resize scroll', function() { | |
// if the section ID is in the viewport, | |
// add the current-menu-item class to its menu item link and remove the class from the other menu item | |
if ($('#marketing-challenges').isInViewport()) { | |
$( 'a.menu-item-link[href="#marketing-challenges"]' ).parent().addClass( 'current-menu-item' ); | |
$( '#menu-item-8' ).removeClass( 'current-menu-item' ); | |
} | |
// otherwise ensure the parent of the menu item link doesn't have the current-menu-item class | |
else { | |
$( 'a.menu-item-link[href="#marketing-challenges"]' ).parent().removeClass( 'current-menu-item' ); | |
} | |
}); | |
})(jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment