Home > Web Front-end > CSS Tutorial > How to Collapse a Bootstrap 3 Navbar on Outside Click?

How to Collapse a Bootstrap 3 Navbar on Outside Click?

Susan Sarandon
Release: 2024-11-29 01:16:11
Original
327 people have browsed it

How to Collapse a Bootstrap 3 Navbar on Outside Click?

Collapsing a Bootstrap 3 Navbar by Clicking Outside Its Elements

Question: How can you automatically minimize an open Bootstrap 3 navbar when clicking outside its bounds? By default, you can only open or close it through the navbar-toggle button.

Example:

[Example and Code](link)

Initial Attempts:

The provided code didn't work:

jQuery(document).click(function() {

});

jQuery('.navbar').click(function(event) {
    jQuery(".navbar-collapse").collapse('hide');
    event.stopPropagation();
});
Copy after login

Solution:

$(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();
        }
    });
});
Copy after login

Explanation:

This code:

  • Listens for clicks anywhere in the document.
  • Checks if the navbar is open and the clicked element is not the navbar-toggle button.
  • If both conditions are met, it simulates a click on the navbar-toggle button, effectively collapsing the navbar.

This approach preserves the navbar's animation and is more user-friendly than manually setting CSS classes.

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

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template