DEV Community

Anna Aitchison
Anna Aitchison

Posted on

7 2

Bootstrap Collapsing Menus without jQuery

Having to use jQuery to enable Bootstrap to do one small thing like a collapsing menu can be a bit overkill. Luckily, however this can easily be worked around.

You can use the same HTML as for any other Bootstrap collapsing navbar, except with a click handler on the navbar-toggler and an ID on the div wrapping the collapsing section.

<nav class="navbar navbar-light bg-white navbar-expand-md">
    <div class="container col-12">
        <a class="navbar-brand" href="/">
            <b>TestSite</b>
        </a>
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbar-list"
            aria-controls="navbarNav" aria-expanded="true" aria-label="Toggle navigation"
            onclick="displayMenu(event)">
            <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbar-list">
            <ul class="nav navbar-nav ml-auto ">
                <li class="nav-item">
                    <a class="nav-link" href="/blog">Blog</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="/tools/">Tools</a>
                </li>

            </ul>
        </div>
    </div>
</nav>
Enter fullscreen mode Exit fullscreen mode

Then simply put this function in a script tag or in a fille and the navbar will work perfectly.

function displayMenu(event) {
    if (document.getElementById("navbar-list").classList.contains("show")) {
        document.getElementById("navbar-list").classList.remove("show")
    }
    else {
        document.getElementById("navbar-list").classList.add("show")
    }
}
Enter fullscreen mode Exit fullscreen mode

If you found this useful, my article How to Use Bootstrap Modals Without jQuery may be interesting to you also.

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more →

Top comments (2)

Collapse
 
feldev profile image
Félix Paradis •

Thanks!
Your solution was not complete enough for me (no transition) but you got me on the right track.

By the way, your function could be reduced to:

function displayMenu(event) {
    document.getElementById("navbar-list").classList.toggle("show");
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
sachind6 profile image
Sachin •

Thank you so much!

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs