Toggle class names
by Terry Young
HTML
<div class="container">
<div class="label">Cat 1</div>
<div class="items">
<div class="item">Item 1</div>
<div class="item">Item 2</div>
</div>
<div class="label">Cat 2</div>
<div class="items">
<div class="item">Item 1</div>
<div class="item">Item 2</div>
</div>
</div>
CSS
div.container {
width: 400px;
margin: 20px;
border: 1px dotted #ddd;
padding: 3px;
}
div.label {
cursor: pointer;
font-family: Arial;
font-size: 9pt;
font-weight: bold;
border: 1px solid #ccc;
margin: 0;
padding: 5px;
}
div.items {
border: 1px solid #ccc;
border-top: 0;
font-family: Arial;
font-size: 9pt;
margin-bottom: 3px;
}
div.item {
width: 90%;
margin-left: 30px;
padding: 5px;
}
div.expanded {
border-bottom: 0;
margin-bottom: 0;
}
div.collapsed {
border-bottom: 1px solid #ccc;
margin-bottom: 3px;
}
JavaScript
$(function () {
$("div.label")
.addClass("expanded")
.on({
click: function () {
var $this = $(this),
s = ["collapsed", "expanded"], // states
i = 1 * $this.hasClass(s[1]); // true = 1, false = 0
// geeky one-liner ahead
$this.removeClass(s[i]).addClass(s[Math.abs(i-1)]).next().toggle(i);
}
});
$('div.container').disableSelection();
});