class TravelTable { constructor(parent, dataPath) { this.parent = document.querySelector(parent); this.dataPath = dataPath; } create() { fetch(this.dataPath) .then((response) => response.json()) .then((data) => this.build(this.parent, data)); } build(parent, data) { parent.innerHTML = ""; let [green, red, yellow, grey] = [ "#afd9ab", "#eeaeab", "#e5edb0", "#d9d7d7", ]; let legendArray = [ { name: "Green", color: green, status: "Open to Canadians", }, { name: "Yellow", color: yellow, status: "Open to Canadians, with restrictions", }, { name: "Red", color: red, status: "Closed to Canadians", }, { name: "Grey", color: grey, status: "Unclear", }, ]; let legend = this.make("div", parent, "travel-legend"); legendArray.forEach((entry) => { let item = this.make("div", legend, "legend-item"); item.innerText = entry.status + " "; item.style.boxShadow = `16px 0 0 0 ${entry.color}`; }); let search = this.make("input", parent, "travel-search"); search.type = "text"; search.placeholder = "Search for country..."; let tableContainer = this.make("div", parent, "travel-table-container"); let table = this.make("table", tableContainer, "travel-table"); let thead = this.make("thead", table); let headRow = this.make("tr", thead); this.make("th", headRow).innerText = ""; this.make("th", headRow).innerText = "Country"; this.make("th", headRow).innerText = "Information"; let tbody = this.make("tbody", table); data.forEach((country, i) => { let row = this.make("tr", tbody); row.dataset.name = country.Country; let flag = this.make("td", row, "table-flag"); flag.style.background = country.Status === "Green" ? green : country.Status === "Red" ? red : country.Status === "Yellow" ? yellow : grey; let name = this.make("td", row); name.innerText = country.Country; let text = this.make("td", row); text.innerText = country.Text; }); let source = this.make("div", parent, "travel-sources"); source.innerText = "Sources: International Air Transport Association, the Canadian Travel and Tourism Roundtable, Travel Off Path"; search.addEventListener("input", () => { Array.from(document.querySelectorAll(".travel-table tr")).forEach( (country) => { if (search.value.trim() === "") { country.style.display = "table-row"; } else if ( country.dataset.name && !country.dataset.name .toLowerCase() .includes(search.value.toLowerCase().trim()) ) { country.style.display = "none"; } else { country.style.display = "table-row"; } } ); }); } make(element, parent, Class = null, Id = null) { let el = document.createElement(element); if (Class) { Class.split(" ").forEach((word) => el.classList.add(word)); } if (Id) { el.id = Id.split(" ")[0]; } if (parent) { parent.append(el); } else { console.log(`Parent element ${parent} doesn't exist.`); } return el; } }