The following example is an accordion script in JavaScript that does not use jQuery. When I started looking for a simple solution to this requirement I did not accept the idea of having to use a powerful and robust library for a simple implementation. I didn't like the idea of use a machine gun when what I really need is a slingshot. So as a jQuery detox process I decide create my own solution. So far the code is simple enough and I’m planning using it in production as a custom widget in my blog running Wordpress. I’m very enthusiast of minimalist development and I have some concerns with this code.
Any suggestions about how I can achieve a simpler and elegant solution? I was thinking in implementing the element.classList
properties.
Here is a live demo of the accordion script.
HTML
<aside id="archives" class="widget widget_archive"><h3 class="widget-title">Archivos</h3>
<ul>
<li><a href="#">2015</a>
<a href="#"<i class="fa fa-angle-down"></i></a>
<ul>
<li><a href="#">febrero 2015</a></li>
<li><a href="#">enero 2015</a></li>
</ul>
</li>
<li><a href="#">2014</a>
<a href="#"<i class="fa fa-angle-down"></i></a>
<ul class="hide">
<li><a href="#">diciembre 2014</a></li>
<li><a href="#">noviembre 2014</a></li>
<li><a href="#">marzo 2014</a></li>
<li><a href="#">febrero 2014</a></li>
<li><a href="#">enero 2014</a></li>
</ul>
</li>
<li><a href="#">2013</a>
<a href="#"<i class="fa fa-angle-down"></i></a>
<ul class="hide">
<li><a href="#">diciembre 2013</a></li>
<li><a href="#">septiembre 2013</a></li>
</ul>
</li>
</ul>
</aside>
CSS
.widget
{
width:60%;
margin:50px auto 0 auto;
border:4px solid rgba(10,10,10,0.05);
padding:10px;
border-radius:10px;
-webkit-box-shadow: 10px 10px 45px -20px rgba(0,0,0,0.75);
-moz-box-shadow: 10px 10px 45px -20px rgba(0,0,0,0.75);
box-shadow: 10px 10px 45px -20px rgba(0,0,0,0.75);
}
.widget-title
{
font-weight:bold;
text-transform:uppercase;
color:#636363;
padding-bottom:10px
}
.widget a
{
color:#9b9b9b;
text-decoration:none;
padding:10px 0 10px 10px;
display:inline-block;
}
.widget a + a
{
padding:10px 16px;
float:right;
line-height:1.5;
}
.widget a + a:hover
{
background-color:#ddd;
color:#fff;
}
.widget a:hover
{
color:#444
}
.widget ul
{
list-style-type:none;
margin:0;
padding:0;
background-color:#eee;
}
.widget ul
{
line-height:1.5;
}
.widget li
{
border-top:1px solid #ccc;
}
.widget li li
{
line-height:1.5;
border-top:1px solid #eaeaea;
background-color:#fff;
}
.widget > ul li:first-child
li a:first-child {
display:inline-block;
}
.hide {
display:none;
}
JS
"use strict";
var elementum = document.querySelector(".widget_archive");
var gestus = elementum.getElementsByClassName("fa");
for (var i = 0; i < gestus.length; i++) {
gestus[i].addEventListener("click", toogle);
}
function toogle()
{
if (this.nextElementSibling.className === "")
{
this.nextElementSibling.className = "hide";
}
else
{
this.nextElementSibling.className = ""
}
}