Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bootstrap collapse without unique identifier

I'm trying to use the bootstrap collapse plugin in such a way that a unique identifier is not required. Normally there is usually a single or a couple of collapsible elements on a page.

But my elements are generated dynamically and passing index keys is overkill.

What happens now is that if I toggle the collapse for element2, it will collapse element1. Obviously because they have the same ID.

Any way to achieve this without actually giving each collapsible element a unique id?

Here's a functional js fiddle:

http://jsfiddle.net/hhvrjnr3/

like image 875
Nick Avatar asked Feb 06 '15 16:02

Nick


1 Answers

It can be done. First remove the data-target="#collapseExample" from the elements you want to collapse. Then add an extra class to your toggle button, I've added 'collapser'. That's not really needed, but it's nice to identify the toggle button. Then add some jQuery to do the toggling, in this case I am using next() to get the subsequent element to the toggle button which is your element you wish to collapse.

$('.collapser').click(function() {
    $(this).next().collapse('toggle');
});

Example jsFiddle

like image 52
DavidG Avatar answered Sep 28 '22 14:09

DavidG