I'm building a personal site that has a project list index. From this list, a user can click on a project and view the content. I have a global function that retrieves the primary class of each project's content, determines the reading time of the content, and returns the class and associated reading time. I also have an empty array that I will push the returned values to after function runs.
//array to store class/reading time pair
const dataPair = [];
//function that retrieves text content, calculates reading time,
// and returns the class + associated reading time
const readTime = function(contentClass) {
const txt = document.getElementsByClassName(contentClass)[0].textContent;
const wordCount = txt.replace( /[^\w ]/g, "" ).split( /\s+/ ).length;
const readingTimeInMinutes = Math.floor(wordCount / 228) + 1;
const readingTimeAsString = readingTimeInMinutes + " minute read";
const readTimeOutput = {
cls: contentClass,
tme: readingTimeAsString
}
return readTimeOutput;
};
On each project page, I have a function that calls the global function and pushes the returned values to the empty array.
(() => {
const output = readTime("project-one");
dataPair.push(output);
})();
My question is - is there a way to execute all of this globally so I can populate the project list index with the reading time of each project as well? The way this is set up now, the returned values are only available once a project page loads so there isn't a way for me to retrieve the reading time to display outside of that page.