Home >Web Front-end >CSS Tutorial >Can I Close a Collapsed Bootstrap 3 Navbar by Clicking Outside It?

Can I Close a Collapsed Bootstrap 3 Navbar by Clicking Outside It?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-15 12:52:02399browse

Can I Close a Collapsed Bootstrap 3 Navbar by Clicking Outside It?

Closing Collapsed Navbar on External Click in Bootstrap 3

Question:

Can an open, collapsed navbar in Bootstrap 3 be closed by clicking outside the navbar area? Currently, the navbar can only be opened or closed by selecting the navbar-toggle button.

Response:

Yes, closing the navbar on external click is possible. Consider the following 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();
        }
    });
});

Explanation:

This modified version of the original answer introduces the following functionality:

  • Checks if the navbar-collapse element has the "in" class, indicating it is open and collapsed.
  • If the navbar is open and the target of the click is not the navbar-toggle button, it triggers a click event on the navbar-toggle button, effectively closing the navbar.

The above is the detailed content of Can I Close a Collapsed Bootstrap 3 Navbar by Clicking Outside It?. 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