Reputation: 51
I need help for hide/collapse navbar after click in a anchor of landind page.
I useded this script for Bootstrap 4.x
<script type="text/javascript ">
$(document).on('click', '.navbar-collapse', function(e) {
if ($(e.target).is('a')) {
$(this).collapse('hide');
}
});
</script>
Example: https://www.codeply.com/p/mtQ5rWH2DA
But, this script not working for Booststrap 5.x.
In this questions How to hide collapsible Bootstrap navbar on click , the user Zim post this code for Boostrap 5 (beta)
const navLinks = document.querySelectorAll('.nav-item')
const menuToggle = document.getElementById('navbarSupportedContent')
const bsCollapse = new bootstrap.Collapse(menuToggle)
navLinks.forEach((l) => {
l.addEventListener('click', () => { bsCollapse.toggle() })
})
I tested the script, and partial work. But, in load/reload the page, the navbar expand for default and not collapseded, is not beautiful this pretty Example: https://www.codeply.com/p/VyAEZuzWzm
Observation:
Zim's script works, but in a little weird way. When loading the page, the menu already appears expanded instead of collapsed and only when clicking does it close.
In other words, I'm trying to have the same behavior as Bootstrap 4.x:
Menu collapsed when loading and/or reloading page > click toogle to open menu > click link / anchor > menu collapses after click
Upvotes: 0
Views: 2154
Reputation: 362360
It's open by default because the script instaniates the Bootstrap Collapse. Simply set the toggle option to false...
const bsCollapse = new bootstrap.Collapse(menuToggle, {toggle:false})
Upvotes: 2