Sorted Flexbox Lists
Joshua HawxwellThis is a technique I haven’t seen anywhere else, so here it is…
Say you have a list of items that you want to be able to filter. Items that don’t match should fade out and be pushed below matching items. Here’s a list to start with,
<input type="text" placeholder="Filter..." />
<ul>
<li>Apple</li>
<li>Apricot</li>
<li>Banana</li>
<li>Bilberry</li>
<li>Blackberry</li>
<li>Blackcurrant</li>
<li>Blueberry</li>
<li>Boysenberry</li>
<li>Cantaloupe</li>
<li>Currant</li>
</ul>
The first step is to make it a flex list:
ul {
display: flex;
flex-direction: column;
}
Then add a class which represents the “hidden” elements, these are made
transparent and pushed to the bottom with order: 1
,
.hidden {
opacity: .3;
order: 1;
}
Finally add a little javascript to apply/remove the class
function filter(val) {
for (var li of document.querySelectorAll("li")) {
if (li.innerHTML.contains(val)) {
li.classList.remove("fade");
} else {
li.classList.add("fade");
}
}
}
document.querySelector("input").onkeyup = function() {
filter(this.value);
}
And it is done. No sorting the list with javascript or anything complex, just simple class manipulation with flexbox. An example should be below to play with: