Samuel Sjöberg's weblog

Skip to navigation

Filtering of lists

One thing I really like with iTunes is the way you search the library. It's fast and easy to use and has the advantage of not reloading the window which makes the user wait for a response.

So, why haven't this been adopted on the web yet? It's easy to implement and could for example be used to find the course you're attending or be combined with a sortable table.

I've put together a test case so you know what I'm talking about.

The script is pretty basic. It loops through the whole list and matches the pattern in the input-field against the node value of the elements. If it's a match it is displayed otherwise not. The script also keeps track of alternating row colors and justifies those according to the visible set of elements.

function applyFilter(filter) {
   var re = new RegExp(filter.value, 'i');
   var items = document.getElementById('target').childNodes;
   var item, i, value, count = 0;
   for (i = 0; (item = items[i]); i++) {
      if (item.nodeType == 1) {
         value = item.firstChild.nextSibling.firstChild.nodeValue;
         if (re.test(value)) {
            item.style.display = 'block';
            item.className = (count++ % 2) ? 'odd' : 'even';
         } else {
            item.style.display = 'none';
         }
      }
   }
}

Above is the core-function. In addition to this I also made a onload-function which setup the alternating colors and give focus to the input-field.

When I wrote this I got to two conclusions:

  1. MSIE6 does not support the lastChild-attribute. I can live without it, but if it where there I could have written item.lastChild.firstChild.nodeValue which is... shorter.
  2. MFF has the really annoying behaviour of making blanks into textNodes. Since MSIE6 doesn't do that and I didn't wanted to
    use li.getElementsByTagName() I removed any white space
    between the tags in the example.

The script should degrade gracefully if I haven't missed out on anything. If you want to keep the filtering-capabilities even when javascript is disabled or the script fails you could submit the page and let the server do the filtering.

Pages linking to this entry

Pingback is enabled on all archived entries. Read more about pingback in the Pingback 1.0 Specification.

About this post

Created 11th November 2004 09:48 CET. Filed under Javascript and DOM.

0 Comments
0 Pingbacks