How to prevent the accordion from switching when you click a button in the header?

I am using the bootstrap accordion class and want to have buttons in the title that can be clicked without switching the accordion. Here is an 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 the onclickc handler e.preventDefault();to stop the accordion from starting, but it did not work:

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

JSFIDDLE

How can I prevent the accordion from starting when I press a button?

+4
source share
1 answer

You want to stop the bubble event, so you use stopPropagation:

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

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

+9
source

Source: https://habr.com/ru/post/1546430/


All Articles