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

How to Close a Bootstrap 3 Collapsed Navbar on Outside Click?

Mary-Kate Olsen
Release: 2024-11-16 17:50:03
Original
790 people have browsed it

How to Close a Bootstrap 3 Collapsed Navbar on Outside Click?

Closing Collapsed Navbar upon Click Outside

To dismiss a collapsed navbar when clicking outside the designated area in Bootstrap 3, the following solution can be implemented:

The task is to establish a mechanism that senses user clicks beyond the navbar element and triggers the closure of the navbar. The initial attempt using jQuery(document).click(function()) and jQuery('.navbar').click(function()) fell short in achieving this goal.

A modified approach incorporates a click event listener on the document element:

$(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

In this code, clickover determines the element where the click occurred. _opened ascertains whether the navbar is currently collapsed and open. Then, if the navbar is open and the click occurred outside the toggle button, the button is programmatically clicked, triggering the navbar closure.

This solution implements a smooth collapsing animation and halts the propagation of the click event to the underlying elements, ensuring the navbar closes upon click outside its bounds.

The above is the detailed content of How to Close a Bootstrap 3 Collapsed 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