Disable collapse for link in a data-toggle element

Karol picture Karol · Jun 9, 2014 · Viewed 19k times · Source

I have a collapsing panel body, like this (the fiddle, which now has the fixed code):

<div class="panel panel-default">
    <div class="panel-heading">
        <div class="panel-title" data-toggle="collapse" href="#collapseOne">
            <a href="#">1) collapsing link</a>
            <a href="#">2) not collapsing link</a>
        </div>
    </div>
    <div id="collapseOne" class="panel-collapse collapse in">
        <div class="panel-body">Anim pariatur cliche ...</div>
    </div>
</div>

The data-toggle is set on the panel title, because I want a click anywhere on it to open the other panel. Except the second link. My goal is to disable the collapsing behavior for the second link. What is the best/simplest way to achieve that?

Important: I do not want to set the data-toggle on the first link only. I want a click anywhere on the panel to trigger the even, except on the second link.

Answer

Jorge Garc&#237;a picture Jorge García · Jun 9, 2014

You need to add a class for those elements that you don't want to fire the collapse event and then stop the event propagation via javascript. So... here is the correct answer.

<div class="panel panel-default">
    <div class="panel-heading">
        <div class="panel-title" data-toggle="collapse" href="#collapseOne">
            <a href="#">1) collapsing link</a>
            <a href="#" class="no-collapsable">2) not collapsing link</a>
        </div>
    </div>
    <div id="collapseOne" class="panel-collapse collapse in">
        <div class="panel-body">Anim pariatur cliche ...</div>
    </div>
</div>

Stop the event propagation like this:

$('.no-collapsable').on('click', function (e) {
    e.stopPropagation();
});