Bootstrap Navbar Collapse not closing on Click
Asked Answered
H

13

10

I'm using Bootstrap an it's collapsed Navbar on a one-page website together with a simple scrolling script, so if I click on a single link the page scrolls down to anchor - works great. However the Navbar does not collapse when I click on a link which covers a lot of content on mobile devices - you first have to click on the toggle which is annoying. I found out that it should help to add the data-toggle and data-target attributes to the links, but it doesn't work at all - where is my mistake?

NAVIGATION:

<nav class="navbar navbar-default mainbar" role="navigation">
    <div class="navbar-header">
        <button type="button" class="navbar-toggle hvr-bounce-to-bottom" data- toggle="collapse" data-target=".navbar-collapse">
          <span class="sr-only">Toggle navigation</span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
        </button>
    </div>

    <div class="collapse navbar-collapse navbar-collapse">
      <ul class="nav navbar-nav">
         <li><a data-toggle="collapse" data-target=".navbar-collapse" href="#link1" class="navelement">Link 1</a></li>

         <li><a data-toggle="collapse" data-target=".navbar-collapse" href="#link2" class="navelement">Link 2</a></li>

       </ul>
     </div>
</nav>

UPDATE: It's a Javascript problem. My smooth-scroll script causes an issue:

  var corp = $("html, body");
  $(".navelement").click(function() {
    var flag = $.attr(this, "href");
    corp.animate({
        scrollTop: $(schild).offset().top - 60
    }, 1600, function() {
        window.location.hash = flag;
    });
    return false;
});

It's a pretty simple script, but I have no clue what to do with it to make the navbar collapse.

Hitherto answered 12/2, 2015 at 8:40 Comment(0)
W
9

Using the above example, what worked for me was to add data-toggle="collapse" data-target=".navbar-collapse" to the outer div

<div class="collapse navbar-collapse" id="my-navbar-collapse">

<div class="collapse navbar-collapse" id="my-navbar-collapse" toggle="collapse" data-target=".navbar-collapse">

The entire menu looks like this with the change:

 <nav class="navbar navbar-expand-xl navbar-light bg-light">
  <a class="navbar-brand" href="#">Main</a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>

  <div class="collapse navbar-collapse" id="navbarSupportedContent" data-toggle="collapse" data-target=".navbar-collapse" >
    <ul class="navbar-nav mr-auto">
      <li class="nav-item active">
        <a class="nav-link" routerLink="/home">Home <span class="sr-only">(current)</span></a>
      </li>
      <li class="nav-item active">
        <a class="nav-link" routerLink="/guitars">Guitars <span class="sr-only">(current)</span></a>
      </li>
      <li class="nav-item dropdown">
        <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
          Dropdown
        </a>
        <div class="dropdown-menu" aria-labelledby="navbarDropdown">
          <a class="dropdown-item" routerLink="/nasa-image">NASA Image</a>
          <a class="dropdown-item disabled" href="#">Another action</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item disabled" href="#">Something else here</a>
        </div>
      </li>
      <li class="nav-item">
        <a class="nav-link disabled" href="#">Disabled</a>
      </li>
    </ul>
   
  </div>
    </nav>
Werner answered 26/6, 2020 at 20:50 Comment(3)
Works perfectly and makes sense. Idea being to couple data and data-target 🎯. – Illation
Perfect solution – Ethel
After the addition, my anchor tags do not work. – Mekka
R
7

I know this is a bit late coming in however, even in Bootstrap 4.0.0-alpha.6; the navbar does NOT inherently close after a menu item selection. The docs at Bootsrap have gotten better - but there is NO clear-cut example on how to get the navbar to close after a new menu selection.

In your html file - you go to the target div for the collapse class - the div I'm sowing below came strait from the Bootstrap site - so nothing has changed on that note:

<div class="collapse navbar-collapse" id="navbarSupportedContent">

You use that id to monitor if the navbar is expanded (out of collapsed mode), then I added a click event to the a.nav-links in the navbar that re-collapses the navbar:

$("#navbarSupportedContent").on('show.bs.collapse', function() {
    $('a.nav-link').click(function() {
        $("#navbarSupportedContent").collapse('hide');
    });
});
Reviere answered 10/7, 2017 at 23:29 Comment(0)
D
4

I would recommend following this a little bit closer to help you out. http://getbootstrap.com/components/#navbar Seems to be what you are basing it off of. Mainly, when you look @ that link, look at the first button line that you have and compare as that is your main drop down on the mobile version which takes up lots of screen real estate as you mentioned.

<nav class="navbar navbar-default mainbar" role="navigation">
    <div class="navbar-header">
        <button type="button" class="navbar-toggle hvr-bounce-to-bottom collapsed" data-toggle="collapse" data-target="#my-navbar-collapse">
          <span class="sr-only">Toggle navigation</span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
        </button>
    </div>

    <div class="collapse navbar-collapse" id="my-navbar-collapse">
      <ul class="nav navbar-nav">
         <li><a data-toggle="collapse" data-target=".navbar-collapse" href="#link1" class="navelement">Link 1</a></li>

         <li><a data-toggle="collapse" data-target=".navbar-collapse" href="#link2" class="navelement">Link 2</a></li>

       </ul>
     </div>
</nav>

1) I changed this part data- toggle="collapse" to data-toggle="collapse". There was just an extra space on line 3.

2) I added an id to your drop down instead of a class to identify more particularly (may not matter) and also changed the name to "my-navbar-collapse" This change was made on lines 3 and 11. Also this previously means you were just using the same class twice on the same element which didn't make sense.

3) I added the class "collapsed" into your class on line 3 located after "hvr-bounce-to-bottom" Should allow it to be collapsed by default, and only show if it is opened by the user.

That should help fix it as it cleans it up. Also, do you have a drop down in your nav bar that needs to be brought back up when you toggle other than the main button you listed? Doesn't seem so as of yet, just asking to make sure it's clear.

Dabster answered 12/2, 2015 at 9:31 Comment(7)
Sorry to say, but I did everything you described and I know it really should work - but after all it doesn't. Somehow feeling stupid :D – Hitherto
Really? I pulled it up on my phone using JSFiddle for me, and it works. Collapsed by default, has 3 icon bars for image, Opens and closes when clicked on. LG G3. jsfiddle.net/camdixon/v2gosj5s – Dabster
Can you test the JSFiddle for me on your phone? Let me know how it does. This way I can be sure it is serving you the fresh version (could always be some old cached version). This way we avoid the phone / computer using a cached version. – Dabster
fascinating: your demo works, I tribble-checked all my code... maybe it's the smooth-scroll plugin that causes the trouble. – Hitherto
Possibly or a cached version if you don't clear it everytime. Usually it's either that or a weird conflict. I've wasted so many hours just by trying to find out which on my projects. Haha, best of luck man! – Dabster
I can say that there is no cache problem - was my first thought, too, seems like there is a really, really, strange bug - will update this post when I discovered it. Thanks for your help! – Hitherto
I would create a separate problem for that. It's really different from what you said on this question. I'm no javascript pro either, so I can't really help you :( You will get a better answer and faster probably by making a new question. – Dabster
P
3

This works for me:

$('.navbar-nav>li>a').on('click', function(){
    $('.navbar-collapse').collapse('hide');
});
Precondemn answered 7/11, 2020 at 17:47 Comment(1)
The other answers have a lot of depth and detail to them. This answer would be greatly improved by both. – Hagiography
A
1

This small jquery snippet works in this way: If navbar is expanded, nothing happens, so no blink (normal bootstrap behavior). If navbar is collapsed, after a click event, closes the navbar. Works on bootstrap 4

  $(".navbar a").click(function(event) {
      // check if window is small enough so dropdown is created
      var toggle = $(".navbar-toggler").is(":visible");
      if (toggle) {
          $(".navbar-collapse").collapse('hide');
      }
  });
.wrapper {
    height: 400px;
}

#div1 {
    background-color: #73683b;
}

#div2 {
    background-color: #B0A084;
}

#div3 {
    background-color: #E9E6FF;
}

#div4 {
    background-color: #B3679B;
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">

<div class="container px-0">
        <nav class="navbar navbar-expand-lg navbar-dark bg-dark mx-0">
            <a class="navbar-brand" href="#">Logo</a>
            <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
          <span class="navbar-toggler-icon"></span>
        </button>

            <div class="collapse navbar-collapse" id="navbarSupportedContent">
                <ul class="navbar-nav mr-auto">
                    <li class="nav-item active">
                        <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="#div1">Link 1</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="#div2">Link 2</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="#div3">Link 3</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="#div4">Link 4</a>
                    </li>
            </div>
        </nav>
    </div>

    <div class="container wrapper d-flex flex-column justify-content-center" id="div1">
        <p class="text-center">DIV 1</p>
    </div>
    <div class="container wrapper d-flex flex-column justify-content-center" id="div2">
        <p class="text-center">DIV 2</p>
    </div>
    <div class="container wrapper d-flex flex-column justify-content-center" id="div3">
        <p class="text-center">DIV 3</p>
    </div>
    <div class="container wrapper d-flex flex-column justify-content-center" id="div4">
        <p class="text-center">DIV 4</p>
    </div>
    
    <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
Amnesia answered 12/6, 2020 at 12:47 Comment(0)
M
1

Just use span tag and add data-bs-toggle="collapse"` data-bs-target=".navbar-collapse" and place that span tag in anchor tag. below is the code

  <nav class="navbar navbar-expand-lg navbar-light bg-light">
            <div class="container">
                <a class="navbar-brand" href="/">Navbar</a>
                <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
                    <span class="navbar-toggler-icon"></span>
                </button>
                <div class="collapse navbar-collapse" id="navbarSupportedContent">
                    <ul class="navbar-nav me-auto">
                        <li class="nav-item active">
                            <a class="nav-link" href="/"><span data-bs-target="#navbarSupportedContent" data-bs-toggle="collapse">Home</span></a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="#About"><span data-bs-target="#navbarSupportedContent" data-bs-toggle="collapse">About</span></a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="#Contact"><span data-bs-target="#navbarSupportedContent" data-bs-toggle="collapse">Contact</span></a>
                        </li>

                    </ul>
                </div>
            </div>
        </nav>
Mortify answered 27/10, 2022 at 13:15 Comment(0)
M
1

The issue was that I had both bootstrap.bundle.min.js and bootstrap.min.js in the head.

Removing one of them works.

Mekka answered 17/2 at 23:35 Comment(0)
F
0

The only problem with the solution above and the JSFiddle (jsfiddle.net/camdixon/v2gosj5s) is that when you are not on a mobile device, and the menu is not collapsed, the menu items blink. E.g. they collapse in place and reopen in place.

To repeat: expand the window of the JSFiddle result so that the menu is not collapsed, then click on a navbar item.

I've sort of solved the issue in addition to the JSFiddle version by altering the collapse data api in bootstrap.js as follows:

//Bootstrap v3.3.4
//line 662:
Collapse.prototype.toggle = function () {

//Added code: 
var mq = window.matchMedia('screen and (min-width: 768px)')
if (mq.matches) return
//End added code

this[this.$element.hasClass('in') ? 'hide' : 'show']()
}

I'd rather not hardcode the min-width, but don't yet know how I would access the media query values in the css (see @screen-sm-min in less).

Falchion answered 31/3, 2015 at 13:37 Comment(2)
I've added an issue (feature?) at bootstrap on github: github.com/twbs/bootstrap/issues/16189 – Falchion
Looks like will not be fixed in bootstrap 3.x. Hoping in 4. github.com/twbs/bootstrap/issues/16189. See also my variation on camdixon's jsfiddle. It accentuates the issue: jsfiddle.net/mikeedson/v2gosj5s/17 – Falchion
P
0
$(document).ready(function () {
        $(".navbar-nav li.trigger-collapse a").click(function(event) {
          $(".navbar-collapse").collapse('hide');
        });
      });
Presswork answered 21/5, 2018 at 14:37 Comment(1)
While this answer is probably correct and useful, it is preferred if you include some explanation along with it to explain how it helps to solve the problem. This becomes especially useful in the future, if there is a change (possibly unrelated) that causes it to stop working and users need to understand how it once worked. – Unloosen
R
0

You just need to add data-toggle and data-target in navbar code. Where class="collapse navbar-collapse navbar-collapse is used.

 <div class="collapse navbar-collapse navbar-collapse" data-toggle="collapse" data-target="#navbar-collapse">
Home (current) Guitars (current) Dropdown NASA Image Another action Something else here Disabled
Rosenblatt answered 8/7, 2020 at 21:39 Comment(0)
I
0

Just use span tag and add data-bs-toggle="collapse"` data-bs-target=".navbar-collapse" to each links. Finally this worked in my project.

<NavLink exact="true" className="nav-link" to="/">`<span data-bs-toggle="collapse"` data-bs-target=".navbar-collapse">Home</span></NavLink>
Instigation answered 6/3, 2022 at 5:4 Comment(0)
D
0

In my case, the tabs had weird behavior and didn't close due to my vue :class bindings

<router-link class="nav-link text-light" :class="{active: checker}" to="/ideas">

This variant works

<router-link class="nav-link text-light" to="/ideas">
Denotation answered 5/12, 2022 at 15:24 Comment(0)
S
0

for bootstrap v5 just add data-bs-target="#navbarNav" data-bs-toggle="collapse" on anchor tags example

<a class="nav-link active " data-bs-target="#navbarNav" data-bs-toggle="collapse" aria-current="page" href="#">Home</a>

Home

Storey answered 8/3, 2023 at 9:25 Comment(1)
This prevents from href="#anchor" to work. – Xenophobe

© 2022 - 2024 β€” McMap. All rights reserved.