#AD Top Online Web Development & Programming Courses | Udemy
Newsletter Screenshot

Calculate the estimated reading time of an article using JavaScript

Last modified January 6th 2021 | GitHub Source Code [GitHub] | #html #js

You’ve probably seen displayed on websites like Medium an estimated reading time. This metric helps users decide if they read the article immediately, or save it for later. In this tutorial we’ll be using JavaScript to calculate the estimated reading time of an article.

First in a HTML document let’s create a dummy article as follows:

<article id="article">
  <h1>Lorem ipsum dolor sit amet</h1>
  <p>
    Minus ullam est commodi facere repudiandae sit. Ab quibusdam totam
    veniam ducimus ut consequatur sit. Ea et nulla quaerat. Et temporibus
    quas numquam quas dolor vero accusantium numquam.
  </p>
  <!-- repeat <p> tag several times here -->
</article>Code language: HTML, XML (xml)

Then where you would like the reading time to be displayed in the page add this:

<p><span id="time"></span> minute read</p>Code language: HTML, XML (xml)

Now for the JavaScript functionality to calculate the reading time:

function readingTime() {
  const text = document.getElementById("article").innerText;
  const wpm = 225;
  const words = text.trim().split(/\s+/).length;
  const time = Math.ceil(words / wpm);
  document.getElementById("time").innerText = time;
}
readingTime();Code language: JavaScript (javascript)

Here’s a breakdown of what the readingTime() function is doing:

  • text – fetch the article text so we can preform the calculations.
  • wpm – average adult reading speed (words per minute).
  • words – calculate total number of words (length) by splitting at each whitespace.
  • time – calculates the read time rounded up to the nearest whole number.

With the time calculated we then output the number into <span id="time"></span>.

That concludes this tutorial, you now know how to display the estimated reading time for an article that can easily be dropped into a blog or news website. If you enjoyed this article we have many other practical Javascript tutorials for beginners so be sure to check them out!

Related Posts

#AD Shop Web Developer T-Shirts