DEV Community

Cover image for Use JS to live-filter an HTML list - Part 3
Michael
Michael

Posted on • Updated on

Use JS to live-filter an HTML list - Part 3

Filter items by search criteria or by date using JavaScript on a static page ⏳

Use a JS library 📦

For more complex behavior, it can make sense to use a lightweight JS library for a more elegant solution. This can be added to your head tag of your HTML page without rewriting your application.

List.js package

I'd like to recommend List.js, as I've had success with this.

Package on NPM: npmjs.com/package/list.js

The docs site linked there explains how to use it for a few situations. Unfortunately the docs are buggy but if you track down Codepen links in the GH repo examples then you can get to the links.

You have to make sure your HTML is setup for filtering and that your JS code references the correct attributes, which I'll cover next.

I found the effort and code needed was low and the pattern is easy to reuse on the site. And benefit of live filtering is great.

Conditions

The condition you filter on could be set by the developer, such as filtering items relative to today's date.

Or could can filter based on user input - perhaps the user can choose a month or category from a drop-list and see only repos or blog posts that match that.

Demo to filter GH repos

I created a demo on CodePen here to showcase list.js, with comments explaining the setup needed.

Initially all repos (4) on page are shown and the you can enter text to live filter on the repo names.

There are 3 parts need for that to work, which I'll cover next.

  • 1. HTML control
  • 2. HTML data
  • 3. JavaScript behavior

1. HTML control 🎛

The first part is HTML control so your user can search.

<div class="field">
    <p class="control">
        <input class="search input" type="text" 
            placeholder="Search repo names" />
    </p>
</div>
Enter fullscreen mode Exit fullscreen mode

If your condition was based on say today's date, then this section could be left out as your code will determine the filter choice.

2. HTML data

The second part of the HTML sets up the data as content to filter.

Here is the content shown with just one item, for readability.

<!-- Mark the outside of the list with "list" class to enable filtering. -->
<div id="repo-cards" class="list">

    <!-- First item here -->
    <div>
        <!-- Use "list-name" to enable for "name" attribute and 
            set "data-name" with the value value to match on. -->
        <p class="title list-name" data-name="aggre-git">
            <a href="https://github.com/MichaelCurrin/artists-portfolio">artists-portfolio</a>
        </p>
        <p>Website with an image gallery, built on Jekyll and the Aperture theme</p>
        <p>Commits: 77</p>
    </div>

    <!-- More items here... -->
</div>
Enter fullscreen mode Exit fullscreen mode

Setup the JavaScript behavior

The list.js package is loaded using a script tag. That setup in the settings of the Codepen and so omitted from the HTML pane.

<script src="//cdnjs.cloudflare.com/ajax/libs/list.js/1.5.0/list.min.js"></script>
Enter fullscreen mode Exit fullscreen mode

After list.js is loaded, you can use the List object. See the JS pane in the Codepen or the snippet below.

var options = {
    valueNames: [
        {
            name: "list-name",
            attr: "data-name"
        }
    ]
};
var userList = new List("repos", options);
Enter fullscreen mode Exit fullscreen mode

Here we enable filtering on the element if ID repos, we say that name of the field list-name and the value of the field will be under the attribute data-name.

You could add more elements to valueNames if you wanted to filter on description or star count or something else for example.

Using list.js on a website

The simplified demo above is based on one of my sites where I've applied list.js to filter my full list of over 100 repos. This is a Jekyll-based static site which is hosted on Netlify.

Here is the markdown for that page:

It uses Jekyll templating to create the repo cards based on data fetched from GitHub (specifically using GraphQL to get topic labels not covered in the REST API).

This templating makes it easy to apply the list.js classes at a large scale. Tip: The library also supports adding items to the list using JS data, if you prefer that over HTML data.

Here is the template for a repo item, including the list.js attributes like "list-name" and "data-name".

API request vs local filtering

Note that in this case, all the repo data is fetched at build time and rendered as static HTML on the page.

This means the site has to be rebuilt in order to show the latest repos changes, but having things outdated by a week or two is okay for my case.

The upfront fetch and then filtering local data later means I don't have to fire off API requests to GitHub API to get repos on every search. You can get throttled easily by the API and get an error if you do too many searches. Also the API request would take time and require the API to be responsive while filtering on local HTML elements is immediate.

jQuery Datatables

I also want to give a mention to jQuery Datatables. I am going to cover this approach briefly as I haven't used it much, I don't know how well it works outside of tables.

jQuery supports datatables, which allows easy sorting and filtering of a table.

Steps to setup:

  1. Load jQuery asset - JS.
  2. Load jQuery datatable assets - CSS and JS
  3. Add a JS function.

Here's a Codepen demo I made:

Conclusion

I hope you feel ready to take what you've learnt and add live filtering to your site, using JS. With or without a JS library.

Let me know in the comments what your solution is - have you found any similar JS libraries that work well for this and that have better documentation?

Image credit: @jtylernix on Unsplash

Discussion (0)