Eleventy - Zero JS charts
It’d be cool to be able to sprinkle in some charts to your website easily. And without a lick of client-side JavaScript.
This is a demonstration of making a bar chart using the chart.css
library. It enables styling a HTML table as a chart without the need for JavaScript. This is great for performance and accessibility.
Making a “post count” bar chart
In this example, I will create a bar chart of presenting blog posts written by year. A bad proxy for writing productivity but an alluring showpiece for a nerd.
The objective is to produce a HTML<table>
as below.
The table includes a list of (utility) classes specific to chart.css
. There is a chart builder app on the chart.css website to help you pick the correct classes while tinkering with the fundamental styling.
Adding the stylesheet from chart.css
to the page will transform the appearance of this table into a bar chart.
Code
We want to produce a “postCounts” Map
like below.
In a previous post, I discussed how you can group posts by year using a groupBy
function. To keep it simple here, I created a filter called byYear
that has similar logic.
I will make a nunjucks template to make the chart and call it chart.njk
. We are going to loop through our “postCounts” map and produce a series of table rows (the <tr>
element) with the year as a header cell (the <th>
element) and the post count as a data cell (the <td>
element). For the data cell, we need to set the --size
CSS variable with the calculated size of the bar. The size is the post count for the year divided by the total post count.
It is not required to include the count as text content for the <td>
element for rendering the chart. I would recommend that you include the data always to make the chart as accessible as possible. You can use the data-hide
utility class to hide the values.
You can explore the rest in the source code.
Source code
The source code is available in this GitHub repo. You can find it as an independent project in the chart folder.
Can you give the repo a star to indicate that this was a worthwhile tutorial please? 🌟
Conclusion
I love the idea of having semantic, accessible, JavaScript-free charts. The power of static site generators is that it enables you to produce premade data-enriched HTML. In this case just dropping in a stylesheet from the chart.css
library will dress up a <table>
as a chart!
The chart.css
library allows you to make bar, column, area, line, and pie charts from HTML tables. It has decent customisation options. If you want to make more advanced charts and have more customisation options, Apache ECharts is probably your best bet. ECharts supports rendering charts in the form of Canvas, SVG, and VML. You will want to check out its server-side rendering (SSR) option for producing charts at build time.