A Super Simple JavaScript Reading Time Calculator for Statamic

If you follow me on Twitter, you likely know that I’m working on converting this site over to Statamic from its current home on Squarespace. Statamic is a very cool platform, and affords you a ton of control over how your site looks and operates.

One really cool feature in Statamic are variable modifiers which let you, well, do modifications to certain variables. The one that caught my eye was the “word_count” modifier. This will return the number of words in whatever variable you throw at it. I want to use it to count the words in my posts, so here’s the HTML template I have for blog posts:

<div class="slug">
    <h1>{{ title }}</h1>
    <em>{{ date }}</em> - <span id="readTime" class="serverData" data-tag="totalWordsTag”>{ content|word_count }</span> minutes
</div>

That outputs the word count of the current article, but I didn’t want to show just word counts, I want to show readers how long it would actually take to read the article they’re looking at.

After doing some quick research, it seems that assuming 200 words per minute is a generally accepted reading speed. So all we have to do is grab the word count element from the HTML, convert it to an integer, divide by 200, and return it to the document. I also wanted to clean up the minutes display a little, so I added in one more step to round the result to the nearest minute.

<script type="text/javascript">
   var totalWords = document.getElementById("readTime").innerHTML;
   var timeToRead = totalWords / 200;
   var timeInt = Math.round(timeToRead);
   document.getElementById("readTime").innerHTML = timeInt;
</script>

You can certainly do more (such as displaying “minue” instead of “minutes” if the total is 1), but I hope this is a convenient starting point for creating your own reading time counter.