Last active
July 6, 2023 19:26
-
-
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
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($){ | |
$(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