Javascript - jQuery - Make menu item Active automatically
There is, as minimum, two ways how to add 'active' class to menu item, to highlight it.
First one is on backend side. Second one is on frontend side.
Now, I talk about variant with frontend side.
So, I choose javascript to decide to add 'active' class to menu item or not.
There is a code for this:
var pathName = window.location.pathname;
// Iterate through each anchor tag within list items
$("ul li a").each(function () {
// Check if the href attribute matches the current URL
if ($(this).attr("href") == pathName) {
// If there is a match, traverse up the DOM hierarchy to find the corresponding list item
$(this).parents('li').each(function () {
// Add the 'active' class to highlight the menu item
$(this).addClass("active");
});
}
});
This script essentially loops through all anchor "a" tags within list items "li" in the specified unordered list "ul". For each anchor tag, it compares its "href" attribute with the current URL (window.location.pathname). If there is a match, it traverses up the DOM hierarchy to find the corresponding list item and adds the 'active' class.
To make the 'active' class visually noticeable in the menu, you can define specific CSS styles for it. For example:
/* Add any desired styling for the active menu item */
.active {
background-color: #3498db; /* Set background color */
color: #fff; /* Set text color */
/* Add any other styling properties as needed */
}
These CSS styles will be applied to the menu item with the 'active' class, visually highlighting the current page in the menu. Adjust the styles according to your design preferences.
Comments