Home >Web Front-end >CSS Tutorial >How to Close a Bootstrap Navbar on External Click?

How to Close a Bootstrap Navbar on External Click?

Barbara Streisand
Barbara StreisandOriginal
2024-11-20 19:56:20365browse

How to Close a Bootstrap Navbar on External Click?

Closing an Open Navbar on External Click Using Bootstrap

When working with a collapsed navbar in Bootstrap 3, it's useful to be able to close it by clicking outside of the navbar area. To achieve this, you can use the following JavaScript code:

$(document).ready(function () {
    $(document).click(function (event) {
        var clickover = $(event.target);
        var _opened = $(".navbar-collapse").hasClass("navbar-collapse in");
        if (_opened === true && !clickover.hasClass("navbar-toggle")) {
            $("button.navbar-toggle").click();
        }
    });
});

This code monitors all document clicks. When it detects a click outside of the navbar element (as determined by the clickover variable), it checks if the navbar is currently open (_opened). If the navbar is open and the clicked element is not the "navbar-toggle" button, it triggers a click on the toggle button, effectively closing the navbar.

The code snippet you provided does not work because it does not check to see if the navbar is already open before trying to close it. Additionally, it uses jQuery('.navbar').click(...), which will also fire on clicks within the navbar, preventing external clicks from closing it.

By utilizing the modified code provided in the answer, you can ensure that an open navbar closes when you click outside of it, enhancing user experience and navigation flow.

The above is the detailed content of How to Close a Bootstrap Navbar on External Click?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn