Add Dynamic Active Navigation Classes to Menus
When navigating a web page, it's common to highlight the active menu item corresponding to the current page. This improves user experience by providing visual cues for the current location within the site hierarchy.
To implement this functionality, we'll utilize JavaScript to identify the current URL and add an "active" class to the appropriate menu item.
How to Add Active Navigation Class Using JavaScript
Let's examine a solution using jQuery's powerful library:
$(function () { var current = location.pathname; $('#nav li a').each(function () { var $this = $(this); if ($this.attr('href').indexOf(current) !== -1) { $this.addClass('active'); } }); });
Explanation:
Important Note:
If the menu contains multiple links pointing to the same page, this approach may not accurately determine the active item. In such scenarios, additional logic may be required to handle these cases.
The above is the detailed content of How Can I Dynamically Add Active Navigation Classes to My Website Menu Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!