Eli Van Rock Eli Van Rock - 5 months ago 9
jQuery Question

How do I make a div to a Bootstrap drop-down

I need to make a div as a dropdown and when clicking on it,
the menu slides and shows its items.

I've tried to implement this but when clicking on the div it doesn't show
it's items at all.

I've used this reference:
http://getbootstrap.com/javascript/#dropdowns-examples

Here's the way I've implemented this:



$(document).ready(function() {
$('.dropdown-toggle').dropdown();
});

.top-bar-margin-top {
margin-top: 43px;
/*padding: 0;*/
}
.top-bar-margin-top a:hover {
text-decoration: none;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
<div class="col-md-2 col-lg-2 top-bar-margin-top">
<div class="dropdown">
<a id="dLabel" href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">
<span class="top-bar-small-title make-it-regular">item</span>
<br />
<span class="top-bar-app-links make-it-regular">Select Item</span>
<span class="caret"></span>
</a>
</div>

<ul class="dropdown-menu" aria-labelledby="dLabel">
<li><a href="#">Item 1</a>
</li>
<li><a href="#">Item 2</a>
</li>
</ul>
</div>





How can it be solved ?

Answer

There's 2 things wrong here:

  1. You're mixing both data-* attributes and JavaScript initialization, it should be either one or the other (maybe this isn't a real problem, but it is unnecessary and messy).
  2. You haven't followed the example correctly, the dropdown trigger and contents need to both be contained within the div with class "dropdown".

Change the HTML to:

<div class="col-md-2 col-lg-2 top-bar-margin-top">
  <div class="dropdown">
    <a id="dLabel" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">
      <span class="top-bar-small-title make-it-regular">item</span>
      <br />
      <span class="top-bar-app-links make-it-regular">Select Item</span>
      <span class="caret"></span>
    </a>
    <ul class="dropdown-menu" aria-labelledby="dLabel">
      <li><a href="#">Item 1</a></li>
      <li><a href="#">Item 2</a></li>
    </ul>
  </div>

</div>

No JS required (just include the bootstrap.js and it should do the rest).

Working fiddle: https://jsfiddle.net/dpjpcfuy/1/