It seems like your dropdown items are being generated dynamically through ajax or server-side scripting.
If that's the case, you can use some CSS and Javascript to hide empty menus, but there are a few things to keep in mind.
Firstly, ensure that your HTML structure is similar to this:
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">Contact Us <span class="caret"></span></a>
<ul class="dropdown-menu" role="menu"></ul>
</li>
Important: Note that there should be no whitespace between the start and end tags of your ul.dropdown-menu
. This is necessary for the CSS :empty
selector to work correctly.
If there are menu items fetched from a database, they should be placed inside the ul.dropdown-menu
as li
elements. If it's empty, the dropdown will remain empty with a caret icon visible.
You can use a bit of CSS to hide the empty dropdown:
ul.dropdown-menu:empty {
display: none;
}
Unfortunately, due to CSS limitations, we can't target the caret directly. So, you may need to utilize a bit of JavaScript/jQuery like this:
$("ul.dropdown-menu:empty").prev("a").children("span.caret").first().hide();
You could implement both solutions using only jQuery if preferred. The presented code snippet gives you an idea of how to handle this situation.
Your setup should now behave similarly to the following example when fully executed. View it in fullscreen mode to prevent any issues.
Example Code Snippet:
$("ul.dropdown-menu:empty").prev("a").children("span.caret").first().hide();
ul.dropdown-menu:empty {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
<nav class="navbar navbar-default" role="navigation">
<ul class="nav navbar-nav">
<li class="active"><a href="#">Home</a></li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">Dropdown <span class="caret"></span></a>
<ul class="dropdown-menu" role="menu">
<li><a href="#">Action</a></li>
<li><a href="#">Another action</a></li>
<li><a href="#">Something else here</a></li>
</ul>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">Contact Us <span class="caret"></span></a>
<ul class="dropdown-menu" role="menu"></ul>
</li>
</ul>
</nav>