DEV Community

Cover image for Menu Active Page
andysaktia
andysaktia

Posted on

3 2

Menu Active Page

When I used scrollspy from bootstrap I realized it only applies to the case within a single page. The following idea came up to make the menu active with a check system from the url.

Container HTML

In my case the nav menu container is like the following.

<div class="classynav">
    <ul id="nav">
        <li class="nav-item">
            <a href="https://example.org/about.php">Tentang</a>  
        </li>
        <li class="nav-item active">
            <a href="https://example.org/project.php">Project</a> 
        </li>
    </ul>
</div>
Enter fullscreen mode Exit fullscreen mode

Script

The principle of this script handle only matches the selected url with the url in the container. For sub menu handlers, I haven't been able to find a meaningful solution, maybe you can use the split attribute ?id for the php web case, or maybe you have an interesting idea, please share it in the comments.

    $(function(){
        var url = window.location.href; 
        $(".classynav a").each(function() {
            var d = $(this).attr('href');
            if(url == d) {
                $(this).closest(".nav-item").addClass("active");
            }
        });
    });
Enter fullscreen mode Exit fullscreen mode

Done

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay