Vanilla JavaScript code snippet that will read all words in a container and create an estimated reading time.
readingTimeBox is the container in which the estimated read time will be displayed.
wordsInPost are the elements that contain the words that will be counted.
Edit the wpm constant to tweak the reading time.
// Guard: if no reading time span on page
if (!document.querySelector(".read-time")) return;
const readingTimeBox = document.querySelector(".read-time"); //The container in which the reading time estimate will be printed
// Count the number of words in each text block
const wordsInPost = wordCount(document.querySelectorAll(".page-content p"))
function wordCount(words) {
let count = 0
for (let i = 0; i < words.length; i++) {
count += words[i].textContent.split(" ").length
}
return count
}
const wpm = 250; //Average words per minute
const readingTimeContent = () => {
// Divide the number of words by the average words per minute
let readingTime = Math.ceil(wordsInPost / wpm);
let readingTimeText = `${readingTime} min`;
return readingTimeText;
}
// Print the total reading time
readingTimeBox.innerHTML = readingTimeContent();