show hide blocks
Animation to show and hide a list of blocks.
by Richard Hunter
HTML
<button data-show>show</button>
<button data-hide>hide</button>
<ul data-container>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
SCSS
ul {
width : 200px;
margin : 100px auto;
background : lightblue;
list-style : none;
padding : 0;
overflow : hidden;
}
li {
width : 50%;
height : 100px;
float : left;
visibility : hidden;
background : red;
}
JavaScript
var listItems = $('[data-container] li');
$('[data-show]').click(function () {
var list = new Iterator(listItems, true);
function showListItem(li) {
$(li).css({
visibility: "visible"
});
}
processList(list, showListItem);
});
$('[data-hide]').click(function () {
var list = new Iterator(listItems, false);
function hideListItem(li) {
$(li).css({
visibility: "hidden"
});
}
processList(list, hideListItem);
});
function Iterator(list, direction) {
this.list = list;
this.index = 0;
this.length = list.length;
// boolean: if false we iterate in reverse direction
this.direction = direction;
}
Iterator.prototype = {
hasNext: function () {
return this.index < this.length;
},
next: function () {
if (this.direction) {
return this.list.get(this.index++);
} else {
return this.list.get(this.length - (++this.index));
}
}
}
function processList(list, strategy) {
if (list.hasNext()) {
strategy(list.next());
setTimeout(function () {
processList(list, strategy);
}, 50)
}
}