Created
October 19, 2019 09:23
-
-
Save manuelricci/2bb89b5655e011805a2280c699a0e341 to your computer and use it in GitHub Desktop.
Show the estimated time to read a content.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Show the estimated time to read a content. | |
* | |
* Usage | |
* | |
* To show the estimated time in your page you need to: | |
* 1 - Include in your page a container with a class that you'll pass to the function | |
* 2 - Call the function passing the text container, the timer container and set echo | |
* to true to show the estimated time. | |
* | |
* To get only the minutes needed to read the content you need to: | |
* 1 - Call the function passing the text container. | |
* | |
* In case the param echo is false the function return only the minutes and nothing else. | |
* | |
* @param {String} contentClass The class that contain the text to read. | |
* @param {String} esitmatedTimeClass The class that will contain the estimated time | |
* @param {Boolean} echo Show the time in the element passed with estimatedTimeClass param | |
* @returns {Void|Number} If echo is true show the estimated time, otherwise it will return the minutes. | |
* | |
* @author Manuel Ricci | |
*/ | |
function estimatedReadingTime(contentClass, esitmatedTimeClass = null, echo = false) { | |
if (echo === true && esitmatedTimeClass === null) { | |
console.error("If you want to show the estimated time you need to specify the param estimatedTimeClass"); | |
return; | |
} | |
const wordPerMinute = 200; // Global average. | |
let content = document.querySelector(contentClass).innerText; | |
let result; | |
content = content.split(" "); | |
if (content.length > 0) { | |
let time = Math.ceil(content.length / wordPerMinute); | |
if (echo) { | |
result = `~ ${time} minuti di lettura`; | |
} else { | |
result = time; | |
} | |
} | |
if (echo) { | |
document.querySelector(esitmatedTimeClass).innerHTML += result; | |
} else { | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment