one day of code

Filter static list using css

January 04, 2021

Filter static list by “using” the gpu :) The three downsides to this are:

  • screen readers are not able to read the total number of items
  • inability to use the relationship operators
  • keyboard navigation will probably take you through all the items (depending on js implementation) and screen reader will not announce them as they are display: none;
<!-- This will serve as a list filter -->
<style id="filter"></style>
<!-- Type the search term here -->
<input id="search" type="search" />
<ul>
<li data-value="xyz"></li>
<!-- the rest of the list items -->
</ul>
<script type="text/javascript">
// Grab the style tag
const filter = document.querySelector('#filter')
// Grab the input control
const input = document.querySelector('#search')
// Make style template to update later
const style = term => `li:not([data-value*="${term}"]) { display: none; }`
// Do the filtering on every input
input.addEventListener(
'input',
e => (filter.innerText = style(e.target.value)),
false
)
</script>

Written by Milan Miljkovic — a tech enthusiast and design system practitioner.