NeoSketo
NeoSketo

Reputation: 525

Bootstrap - How to keep drop-down menu open when sub-menu is open

I am having difficulty trying to keep my drop-down menu open when i click on a sub menu. You would think that Bootstrap would do this right out the box. But i cant find any documentation on it.

here is what i found as a solution: https://www.bootply.com/rgvY6oPO1J

In my HTML i have this:

<div class="btn-group" id="myDropdown">
  <a class="btn dropdown-toggle" data-toggle="dropdown" href="#">
    Menu
    <span class="caret"></span>
  </a>
  <ul class="dropdown-menu">
    <li><a href="#">Choice1</a></li>
    <li><a href="#">Choice2</a></li>
    <li><a href="#" id="btn-mynumbers" data-toggle="collapse" data-target="#mynumbers" aria-expanded="false">Numbers</a>
      <ul class="nav collapse" id="mynumbers" role="menu" aria-labelledby="btn-mynumbers">
        <li><a href="">1</a></li>
        <li><a href="">2</a></li>
        <li><a href="">3</a></li>
        <li><a href="">4</a></li>
        <li><a href="">5</a></li>
      </ul>
    </li>
    <li><a href="#">Choice3</a></li>
    <li class="divider"></li>
    <li><a href="#">Choice..</a></li>
  </ul>
</div>

And here is whats in my JavaScript:

$("#btn-mynumbers").on("click", function (e) {
    e.stopPropagation();
    $("#mynumbers").slideToggle("fast");
});

for the most part it works. But I'm going to have a lot of menu items and i don't want to make a on click caller for every sub-menu i create.

So i tried putting

onclick="Toggle(this);"

in

id="btn-mynumbers"

and creating the function:

function Toggle(element) {
    event.stopPropagation();
    var parentid = element.id;
    var childid = $(parentid).children("ul").attr("id");
    $(childid).slideToggle("fast");

}

so i can give every sub-menu click the ability to stay open. but the event stopped ALL propagation, even the slideToggle. I don't know how to keep the drop down open when a sub-menu slides down.

Upvotes: 3

Views: 2505

Answers (1)

syciphj
syciphj

Reputation: 996

It seems like there was an error with the function you made since event would probably be undefined. I changed it to something like below. But you can see it in action with the codepen link below.

$(".submenu").on("click", function (event) {
  event.stopPropagation();
  var target = event.currentTarget;
  $(target).siblings('ul').slideToggle("fast");
});

The best approach if you don't want to put an id for every possible menu item that has a sub-menu, then work with classes. That way you don't need to recode.

I made you a codepen that shows how to use classes instead of ids as identifiers. I added a sample of another menu item with a sub-menu for you to play around with.

Hope that helps!

Upvotes: 1

Related Questions