1

I have a Bootstrap v3 Panel with a panel-heading and panel-body. I want a user to be able to click on the panel-heading and it will collapse/expand the panel-body. I am using Bootstrap's Collapse javascript to do this. Here is my markup:

<div class="panel panel-default group-panel">
  <div class="panel-heading" role="button" data-toggle="collapse" data-target="#panel-body-foobar">
    <a href="#" class="btn btn-xs">Action Button</a>
  </div>
  <div class="panel-body collapse in" id="panel-body-foobar">
    Some content here. 
  </div>
</div>

This code works fine, clicking on the panel heading will collapse/expand the body. However, notice that I also have a button inside the panel heading. When I click that button, it is collapsing/expanding the panel body. See this jsfiddle if you don't know what I mean.

How can I configure this so that only clicking directly on the panel heading, not any child elements, will trigger the collapsing/expanding?

Joseph
  • 12,678
  • 19
  • 76
  • 115

1 Answers1

2

I believe the solution is to define my own click handler (rather than using the one Bootstrap sets up automaitcally) which ignores clicks on children:

$('.panel-heading[data-toggle^="collapse"]').click(function(){
    var target = $(this).attr('data-target');
    $(target).collapse('toggle');
}).children().click(function(e) {
  e.stopPropagation();
});

Thanks to this answer for helping me figure out how to have a jQuery click handler ignore the clicks on children. Note that due to use of e.stopPropagation();, this does not disable any click handlers on the children themselves.

Community
  • 1
  • 1
Joseph
  • 12,678
  • 19
  • 76
  • 115
  • The solution would simply be to stop even propagation from the button in the panel heading, and nothing more: https://jsfiddle.net/mwxea7qn/1/. You don't need to do anything else on `data-toggle` nor `data-target` attributes. – Igwe Kalu Nov 15 '15 at 21:38
  • Indeed, but that requires me to place that line in the click handlers for all children. In my question, I wanted to keep it simple, so I only included a single button, but in my actual project I do have multiple buttons so placing this on the panel-heading seems to make sense. – Joseph Nov 15 '15 at 21:44
  • You don't have to select by ID. Here's a demonstration that extends my initial point to address the concern you shared above: https://jsfiddle.net/mwxea7qn/2/ – Igwe Kalu Nov 16 '15 at 21:21
  • Thanks, now I see what you're saying. Your answer is definitely a valid one. – Joseph Nov 21 '15 at 04:33