JavaScript: how to highlight the current page in a navigation menu

JavaScript: how to highlight the current page in a navigation menu

In this article, we'll show you how to create a simple JavaScript function to highlight the current page in the navigation menu.

One of the common tasks in creating a website is to highlight the current page in the navigation menu. This helps users understand which section of the site they are in and maintain a consistent browsing experience. In this article, we'll show you how to create a simple JavaScript function to highlight the current page in the navigation menu.

Let's create a JavaScript function that identifies the link corresponding to the current page and assigns it an additional class for highlighting.


function highlightCurrentPage() {
    const currentPageUrl = window.location.href;
    const menuItem = document.querySelector('#menu a[href="' + currentPageUrl + '"]');

    if (menuItem) {
        menuItem.classList.add('active');
    }
}

The first line of code declares a variable called currentPageUrl and assigns it the value of the current page URL using window.location.href. window.location is the object representing the URL of the current page in the browser.

The second line of code uses the CSS query selector to select an element in the HTML document with an ID of menu and an a element with a href which matches the URL of the current page. Basically, look for a link in the navigation menu that points to the URL of the current page.

The third line of code checks if a matching element was found using the query selector. If menuItem is not equal to null (that is, if a matching item was found), the code block inside the if.

Within the if block, a class name active is added to the menuItem element. The active class can be used to apply a special style to the menu link corresponding to the current page.