Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent accordion from toggling when button in header is clicked?

I'm using bootstrap's accordion class and want to have buttons in the header that can be clicked without toggling the accordion. Here's example HTML:

<div class="body">
    <div class="panel panel-default" style="width: 80%">
        <div class="panel-heading" data-toggle="collapse" data-target="#container1" style="cursor: pointer;">
            <h4 class="panel-title" style="display: inline-block;">
               title
            </h4>
        <div style="float: right; width: 130px; text-align: right;"><span style="color: red;">test</span></div>
            <button type="button" class="btn btn-xs btn-primary" style="float: right;" onclick="foo(event);">Button</button>
    </div>
    <div id="container1" class="panel-collapse collapse">
        <div class="panel-body">
            panel content
        </div>
    </div>
    </div>
</div>

I tried using an onclick handler with e.preventDefault(); to stop the accordion from triggering, but it didn't work:

window.foo = function(e) {
    console.log("foo");
    $(".body").append("<br>foo");
    e.preventDefault();
}

JSFIDDLE

How can I prevent the accordion from triggering when the button is clicked?

like image 647
Nate Avatar asked Jun 28 '14 18:06

Nate


1 Answers

You want to stop event bubbling, so you use stopPropagation:

window.foo = function(e) {
    e.stopPropagation();
}

Demo: http://jsfiddle.net/Bye8K/3/

like image 89
dfsq Avatar answered Oct 22 '22 02:10

dfsq