Accordion Logic
Zepto for DOM manipulation
by Anov Siradj
HTML
<ul id="acc"></ul>
CSS
span.content {
display: block;
}
span.hidden {
display: none;
}
JavaScript
String.prototype.format = function(substitutions) {
return this.replace(/\{([A-Za-z0-9]+)\}/g, function(match, key) {
return substitutions[key] !== undefined ? substitutions[key] : ''
})
};
var showhide = function showhide() {
hideAll();
var content = this.find('.content');
if (content.hasClass('hidden')) {
content.removeClass('hidden');
} else {
content.addClass('hidden');
}
};
var hide = function hide() {
if (!this.hasClass('hidden')) {
this.find('.content').addClass('hidden');
}
};
var acc = $('#acc');
var elements = [
{id: 'one',
name: 'One',
content: 'Some content for One'
},
{id: 'two',
name: 'Two',
content: 'Some content for Two'
}
];
var hideAll = function() {
elements.forEach(function(item) {
item.el.hide();
});
};
elements.forEach(function(item) {
acc.append('<li id="{id}">{name}<span class="content hidden">{content}</span></li>'.format(item));
item.el = $('#{id}'.format(item));
item.el.hide = hide;
item.el.on('click', showhide.bind(item.el));
});