Skip to content

Instantly share code, notes, and snippets.

@thierrypigot
Last active July 6, 2023 19:26
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thierrypigot/0ebfa54351564a1d54156c07200d4756 to your computer and use it in GitHub Desktop.
Save thierrypigot/0ebfa54351564a1d54156c07200d4756 to your computer and use it in GitHub Desktop.
[Beaver Builder] Highlight menu links on a One Page with anchor links and sections detection on scroll
(function($){
$(document).ready(function(){
/**
* This part handles the highlighting functionality.
* We use the scroll functionality again, some array creation and
* manipulation, class adding and class removing, and conditional testing
*/
var aChildren = $("header ul.menu li").children(); // find the a children of the list items
var aArray = []; // create the empty aArray
for (var i=0; i < aChildren.length; i++) {
var aChild = aChildren[i];
var ahref = $(aChild).attr('href');
aArray.push(ahref);
} // this for loop fills the aArray with attribute href values
$(window).scroll(function(){
var windowPos = $(window).scrollTop(); // get the offset of the window from the top of page
var windowHeight = $(window).height(); // get the height of the window
var docHeight = $(document).height();
for (var i=0; i < aArray.length; i++) {
var theID = aArray[i];
var menuHeight = $('header.fl-page-header').height();
if( $('body').hasClass('admin-bar') ) {
menuHeight = menuHeight + 32;
}
var divPos = $(theID).offset().top - menuHeight; // get the offset of the div from the top of page
var divHeight = $(theID).height(); // get the height of the div in question
if (windowPos >= divPos && windowPos < (divPos + divHeight)) {
$("header ul.menu li a").blur();
$("a[href='" + theID + "']").parent().addClass("current-menu-item");
} else {
$("header ul.menu li a").blur();
$("a[href='" + theID + "']").parent().removeClass("current-menu-item");
}
}
if(windowPos + windowHeight == docHeight) {
if (!$("header ul.menu li:last-child").hasClass("current-menu-item")) {
var navActiveCurrent = $(".current-menu-item").attr("href");
$("a[href='" + navActiveCurrent + "']").removeClass("current-menu-item");
$("header ul.menu li:last-child").addClass("current-menu-item");
}
}
});
});
$(document).ready(function(){
$("header ul.menu a").on('click',function(){
$("header ul.menu li").removeClass('current-menu-item');
var id = $(this).parent().index();
$( "header ul.menu" ).each(function( index ) {
$( this ).find( "li:eq("+ id +")" ).addClass('current-menu-item');
});
});
});
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment