Vince Ashby-Smith
Vince Ashby-Smith

Reputation: 1192

Nested bootstrap 3.1.1 collapse

Hi i wonder if someone can help. I'm using Bootstrap 3.1.1 and using nested collapse menus for a sidenav. I want to add a background colour (using a class) to the open menu and remove the background colour on the menu close.

This is working fine, however when i have nested menus the code i'm using removes the background colour for the parent item when closing the child menu and i can't work out how to only remove the background colour if its a top level menu close. So if its a child menu this should not remove the background colour when closing the child menu.

$(".nav-sidenav > li").on("show.bs.collapse", function () {
    $(this).addClass("sidenav-active-background");
});
$(".nav-sidenav > li").on("hide.bs.collapse", function () {
    $(this).removeClass("sidenav-active-background");
});

Please see JSFiddle

Upvotes: 1

Views: 1417

Answers (1)

clurect
clurect

Reputation: 359

First you need to remove the '>' n the hide. That will make it cover all the list items in the nav. Then you need to add 'e' to the callback function. Lastly add e.stopPropagation() to keep the parent element from trigger in the event and removing the class.

Goes from

 $(".nav-sidenav > li").on("hide.bs.collapse", function () {
  $(this).removeClass("sidenav-active-background");
 });

To

$(".nav-sidenav li").on("hide.bs.collapse", function (e) {
  e.stopPropagation();
  $(this).removeClass("sidenav-active-background");
});

http://jsfiddle.net/clurect/TF2Tg/1/

Some tips: I'd used hidden.bs.collapse for visual aesthetics. Also you can put in checks to ensure which list item the event triggered on.

Upvotes: 3

Related Questions