ArticleZip > Add Active Navigation Class Based On Url

Add Active Navigation Class Based On Url

Adding an active navigation class based on the URL is a useful way to enhance user experience on your website. It helps users easily identify which section or page they are currently viewing. In this article, we'll guide you through the process of implementing this feature on your website.

To start, you'll need to have a bit of knowledge about HTML, CSS, and JavaScript. Don't worry if you're not an expert in these languages; we'll break it down in simple steps for you.

### Step 1: HTML Setup
In your HTML code, make sure each navigation item has a unique ID or class. This will allow us to target each item later with JavaScript. For example:

Html

<ul>
    <li id="home"><a href="index.html">Home</a></li>
    <li id="about"><a href="about.html">About</a></li>
    <li id="services"><a href="services.html">Services</a></li>
    <!-- Add more navigation items as needed -->
</ul>

### Step 2: CSS Styling
Next, let's style the active navigation class in your CSS file. This class will highlight the current page or section in the navigation bar. For example:

Css

.active {
    color: #ff7700; /* Change color as desired */
    font-weight: bold;
}

### Step 3: JavaScript Implementation
Now, let's add some JavaScript to detect the current URL and apply the active class to the respective navigation item.

Javascript

document.addEventListener("DOMContentLoaded", function() {
    var currentUrl = window.location.href;
    var menuItems = document.querySelectorAll("nav ul li");

    menuItems.forEach(function(item) {
        var itemUrl = item.querySelector("a").href;
        if (currentUrl === itemUrl) {
            item.classList.add("active");
        }
    });
});

### Step 4: Test and Adjust
Finally, save your changes and test the functionality on your website. Navigate through different pages to see the active class in action. If you encounter any issues, you may need to adjust the JavaScript code accordingly.

### Conclusion
By adding an active navigation class based on the URL, you can improve user navigation and provide a more intuitive browsing experience. Remember to keep your code clean and organized for easier maintenance in the future.

We hope this guide has been helpful in implementing this feature on your website. Happy coding!

×