Filter items by search criteria or by date using JavaScript on a static page ⏳
Plain JavaScript approach ☕️
Here I cover how to live filter HTML elements using plain vanilla JavaScript.
When I went on tour in 2019 with my band, "The Buckfever Underground", we have had a long list of upcoming shows on our homepage. We did 21 shows in 16 days... that was crazy and exhausting but epic. Here's our latest album if you want to hear what improvized music with spoken world sounds like The Last Days of Beautiful.
I knew that the concert list would be frozen on the day I built the Jekyll site and would not auto-update. So I decided to add JS filtering on the frontend to make it dynamic.
I setup my data in an array of key-value pairs. Here is a shortened version:
var tour = [
{
date: "2019-04-11",
title: "Stellenbosch – Trude Gunther se huis",
},
{
date: "2019-04-12",
title: "Bainskloof (Wellington) - McBains",
},
// ...
{
date: "2019-04-26",
title: "Evening: Cape Town - Alma Café",
}
];
And then I filtered the array, only rendering the element if the date of the concert was on or after the current date, so that that the list would get shorter which each passing day.
var today = new Date();
// Fix today's time at midnight.
today.setUTCHours(0, 0, 0, 0);
var upcomingShows = tour.filter(show => new Date(show.date) >= today);
Since JS runs in the browser on page load, the value of "today" will always be up to date, compared with a static build where today
is setup once and then left.
Here's the full solution on GitHub. show_list.html
I found that this solution worked really well.
I was able to test it locally as well, by hard-coding past and future dates in place of today, so I can see that it actually works.
Continue on to Part 3 - Use a JavaScript library.
Top comments (0)