Home >Web Front-end >CSS Tutorial >How to Collapse a Bootstrap 3 Navbar on Outside Click?
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(); });
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(); } }); });
Explanation:
This code:
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!