// DOM Element
const list = document.querySelector("ul");
// Constants
const WORDS = [
"Aristotle",
"Heraclitus",
"Parmenides",
"Pythagoras",
"Socrates",
];
// API Data Map
const DATA_MAP = {};
// Initialize the app
(function main() {
initList();
addHoverListeners();
})();
/**
* Initialize the list and add the list items to DOM
*/
function initList() {
WORDS.forEach(appendWordToList);
}
/**
* Adds list item to DOM
*
* @param {String} word
*/
function appendWordToList(word) {
const li = document.createElement("li");
li.style.setProperty("margin-top", "2rem");
li.innerHTML = `${word}`;
list.appendChild(li);
}
/**
* Add listeners for hover and unhover
*/
function addHoverListeners() {
const wordAnchors = document.querySelectorAll("a");
wordAnchors.forEach((wa) => {
wa.addEventListener("mouseover", onHoverWord);
wa.addEventListener("mouseout", onUnhoverWord);
});
}
/**
* Fetches data from API or DATA_MAP and shows its card
*
* @async
* @param {Event} e mouseover event
*/
async function onHoverWord(e) {
const word = e.target.innerText;
const data = await fetchInfo(word);
createCard(data, e.target.parentElement);
}
/**
* Removes card on unhover
*
* @param {Event} e mouseout event
*/
function onUnhoverWord(e) {
const li = e.target.parentElement;
const a = li.querySelector("a");
li.innerHTML = "";
li.appendChild(a);
}
/**
* Shows the card on hover
*
* @param {Object} data
* @param {HTMLLIElement} li list item
*/
function createCard(data, li) {
const card = document.createElement("div");
card.style = `width:260px;max-height:150px;overflow:scroll;background:#fafafa;padding:0.4rem;border-radius:0.2rem;margin-top:0.5rem;`;
card.innerHTML = data.extract_html;
li.appendChild(card);
}
/**
* If information available in DATA_MAP, gets from there
* Else, fetches information from API and stores in DATA_MAP
*
* @param {String} word
* @returns Promise