Skip to content Skip to sidebar Skip to footer

Close Bootstrap Dropdown After Link Click

I have a bootstrap dropdown menu below. It has a link in it hooked up to a knockout.js binding, that returns false because I don't want the # tag to be sent to the browser URL. H

Solution 1:

Give your links a class (e.g. download):

<a href="#" class="download" data-bind="disable: noResults()....

And your dropdown an id (e.g. dlDropDown):

<button class="btn dropdown-toggle" id="dlDropDown" data-toggle="dropdown" data-bind="enable: !noResults()">

And then add the following event handler:

$("a.download").click(function() {
   $("#dlDropDown").dropdown("toggle");
});

Solution 2:

This will actually work with your existing bootstrap markup without having to add any new classes or ids. Hopefully this is helpful to someone else just looking to drop a solution in without changing anything existing.

$(".dropdown-menu a").click(function() {
    $(this).closest(".dropdown-menu").prev().dropdown("toggle");
});

Solution 3:

This can be achieved with bootstraps own CSS class dropdown-toggle

Just add that class to your link elements like so: <a class='dropdown-toggle'></a> and it will toggle the dropdown.


Solution 4:

I think this will close all dropdowns and expanded navmenus on the page:

$('.in,.open').removeClass('in open');

Solution 5:

I unfortunately had no success using .dropdown('toggle') as suggested above...

What did work however was applying bootstrap's dropdown button data attributes to it's own dropdown links:

<button type="button" data-toggle="collapse" data-target=".navbar-collapse" class="navbar-toggle navbar-btn">

...

<ul class="nav navbar-nav">
  <li><a href="#about" class="scroll-to" data-toggle="collapse" data-target=".navbar-collapse">About</a></li>

All I did was add the data-toggle="collapse" and data-target=".navbar-collapse" to each dropdown nav link.

No additional css or js and it worked like a charm :)


Post a Comment for "Close Bootstrap Dropdown After Link Click"