WordBear WordBear - 7 months ago 13
Javascript Question

Need a Simple Collapsible Gizmo

This is kind of weird; I've been learning jQuery and Bootstrap, and both have so many cool tools, yet I'm stumped on one of the easiest tricks in the book: a simple collapsible element.

I found the perfect candidate here:

<div data-role="collapsible">
<h3>I'm a header</h3>
<p>I'm the collapsible content. By default I'm closed, but you can click the header to open me.</p>
</div>


The only problem is that it's jQuery MOBILE, and I'm not sure if it's a good idea to bloat my code with more JavaScript and JS. So before I implement jQuery Mobile, I'd like to ask if anyone can recommend an alternative that works with jQuery, Bootstrap, etc.

One problem is that I'm trying to make a multi-level gizmo. Clicking the initial button or heading will reveal a series of buttons like these:

<button id="na" class="btn btn-na"><b>North America</b></button>
<div id="div-na"></div>
<button id="sa" class="btn btn-sa"><b>South America</b></button>
<div id="div-sa"></div>


Clicking on North America, etc. will invoke AJAX to display a list of countries. One problem I'm having is that, when I click the North America button the "I'm a header" it's nested inside closes.

Another possibility is to reverse engineer the headers in my main content, which can be manually opened or closed...

<ul class="ulMain">
<li data-toggle="collapse" data-target="#d1"><a href="#introduction" title="Introduction" class="NavLink">&#8226; D1 <small><span class="only-collapsed glyphicon glyphicon-chevron-down"></span><span class="only-expanded glyphicon glyphicon-remove-sign"></span></small></a></li>

<div id="d1">D1</div>
</ul>


But I haven't figured out how to change the default setting from expanded to collapsed.

In summary, I'm just looking for a very simple gizmo that 1) hides content by default and 2) doesn't close after being opened until a user clicks on it again. In fact, I thought there was a way to do this with simple CSS, but I can't remember it.

Answer

Bootstrap collapse/accordion can hide the content by default, just omit the in class from the first panel in the example: http://getbootstrap.com/javascript/#collapse-example-accordion

As far as keeping the panels open until their header is selected again, without adding js, there is a great answer for that here: http://stackoverflow.com/a/11658976/2460535

Short answer: Try bootstrap accordions and exclude data-parent='#idofAccordion'

https://jsfiddle.net/curtisweeks/jujL376j/