This article explains how to display the estimated reading time for a news story or article on any website using JavaScript. This metric helps users decide whether to read the article right away or save it for later.
We’ll use JavaScript to calculate the estimated reading time for an article. First, let’s create a dummy article in the HTML document 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>
Then, wherever you want the reading time to appear on the page, add the following code:
<p><span id="time"></span> minute read</p>
And now let’s add the JavaScript functionality to calculate the estimated reading time for the article:
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();
Below, we’ll describe what the function does readingTime():
text— Retrieve the article text so we can perform calculations; parse the node with IDarticle;wpm— set a constant—the average reading speed of an adult (words per minute);words— calculating the total number of words (length) by splitting the text at spaces;time— calculating the reading time and rounding it to the nearest whole number.
After calculating the time, we output this number to <span id="time"></span>.
That’s it. Now we know how to display the estimated reading time for an article, which can easily be embedded in a blog or on a news site.