Skip to content

Instantly share code, notes, and snippets.

@generatepress
Last active April 14, 2020 07:05
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save generatepress/ceba614f8fbaf1b433fc947190ba5841 to your computer and use it in GitHub Desktop.
Save generatepress/ceba614f8fbaf1b433fc947190ba5841 to your computer and use it in GitHub Desktop.
Highlight the current menu item for one page site and sticky navigation
<script type="text/javascript">
(function($) {
$(document).ready(function() {
var navChildren = $("#primary-menu li").children();
var aArray = [];
for (var i = 0; i < navChildren.length; i++) {
var aChild = navChildren[i];
var ahref = $(aChild).attr('href');
aArray.push(ahref);
}
$(window).scroll(function() {
var windowPos = $(window).scrollTop();
var windowHeight = $(window).height();
var docHeight = $(document).height();
for (var i = 0; i < aArray.length; i++) {
var theID = aArray[i];
var secPosition = $(theID).offset().top;
secPosition = secPosition - 135;
var divHeight = $(theID).height();
divHeight = divHeight + 90;
if (windowPos >= secPosition && windowPos < (secPosition + divHeight)) {
$("a[href='" + theID + "']").parent().addClass("current-menu-item");
} else {
$("a[href='" + theID + "']").parent().removeClass("current-menu-item");
}
}
});
});
})(jQuery);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment