cboettig
cboettig

Reputation: 12717

twitter-bootstrap js to toggle all collapse for all elements of a common class

I have a bunch of elements (code-blocks) I'd like to be able to collapse using twitter-bootstrap's javascript, such as

some text

<div class="highlight">
code code
</div>

some more text text 

<div class="highlight">
code code
</div>

I can add the following javascript to make all of these elements collapse:

$('highlight').collapse({
  toggle: true
})

Now I'd like to add a button to toggle the collapse/show for these elements. Any ideas?

Solution requirements

I'm looking for a solution that

  1. extends but doesn't have to change the original html with the code blocks. For instance, I cannot add ids to the 'highlight' divs or more divs around the code blocks.
  2. In a similar goal, I'd like it to apply to all highlight class divs.

Note that using the normal collapse class from twitter bootstrap, such as:

<a href="#block1" data-toggle="collapse">toggle</a>
<div class="collapse" id="#block1">
code code
</div>

doesn't gneralize in this way, since it needs ids, and if they are repeated, it only toggles the first one

Upvotes: 1

Views: 7351

Answers (1)

Jason Kulatunga
Jason Kulatunga

Reputation: 5894

twitter bootstrap uses jQuery behind the scenes so you should just be able to add a button, then add a click event to collapse the code blocks.

<input type="button" value="show/hide" id="toggle_code" />
$(function(){
    $('#toggle_code').click(function(){
        $('.highlight').collapse({
          toggle: true
        })
    });

});

Upvotes: 1

Related Questions