ArticleZip > How To Set Active Class To Nav Menu From Twitter Bootstrap

How To Set Active Class To Nav Menu From Twitter Bootstrap

Twitter Bootstrap provides a convenient way to make our website navigation menus interactive and visually appealing by allowing us to set an active class to the current menu item. This not only enhances user experience but also helps in highlighting the page the user is currently on. In this article, we will walk you through how to set an active class to the navigation menu items using Twitter Bootstrap.

Firstly, it’s important to ensure that you have included the Bootstrap CSS and JavaScript files in your project. If you haven’t done this yet, you can easily include them by adding the following lines to your HTML file:

Html

Next, let’s dive into the actual implementation. To set the active class in the navigation menu, we need to use JavaScript and jQuery. We will create a script that adds the active class dynamically based on the URL of the page. Here’s a step-by-step guide to achieve this:

1. Identify the current page URL:

Javascript

var url = window.location;

2. Get the path from the URL:

Javascript

var path = url.pathname;

3. Update the active class based on the URL:

Javascript

$('.nav-item a').each(function () {
    if ($(this).attr('href') === path) {
        $(this).closest('.nav-item').addClass('active');
    }
});

In the above script, we are iterating through each navigation item and comparing its `href` attribute with the current path. If they match, we add the class `active` to the parent element to highlight the current menu item.

To make this work, ensure that your navigation menu items have the `nav-item` and `nav-link` classes added to them. Here’s an example of how your HTML structure should look like:

Html

<ul class="nav">
    <li class="nav-item">
        <a class="nav-link" href="/home">Home</a>
    </li>
    <li class="nav-item">
        <a class="nav-link" href="/about">About</a>
    </li>
    <li class="nav-item">
        <a class="nav-link" href="/contact">Contact</a>
    </li>
</ul>

By following these steps and incorporating the provided script into your project, you can effectively set the active class to the navigation menu items based on the current page, enhancing the navigational experience for your website users. So go ahead, implement this feature, and make your website's navigation more user-friendly with Twitter Bootstrap!

×