Ensuring that your menu items display the correct active state colors is crucial for providing a clear and intuitive navigation experience, especially on a one-page website.
If you’re encountering issues with the active menu item colors displaying incorrectly in Divi, we are going to cover in this article a fix to the problem.
If you have multiple sections on the page and use the full URL to link to them (e.g., http://yourwebsite.com/#section-1 instead of #section-1), all the menu items will show up as active because, technically, the page shown is the same.
To be able to fix this, we will need to use a simple JS script that will properly add the current-menu-item class to the element that was clicked while at the same time removing the default current-menu-item during page load.
The CSS class that WordPress adds for those menu items must be correctly adjusted only for the menu item that was clicked/linked.
<script>
(function ($) {
$(document).ready(function () {
function menu_anchor_highlight() {
var menu_items_links = $(".nav li a, .et_mobile_menu li a"); menu_items_links.each(function () {
if ($(this).is('[href*="#"]')) {
$(this).parent().removeClass('current-menu-item current-menu-ancestor current_page_item'); $(this).on('click', function () {
var current_index = $(this).parent().index(), parent_element = $(this).closest('ul'); parent_element.find('li').not(':eq(' + current_index + ')').removeClass('current-menu-item current-menu-ancestor current_page_item'); $(this).parent().addClass('current-menu-item current-menu-ancestor current_page_item');
})
}
})
}
setTimeout(function () {
menu_anchor_highlight();
}, 500)
});
})(jQuery);
</script>
The above script needs to be placed in the Divi → Theme Options → Integration tab → Header.
The result of the above script can be seen in the GIF below: