baseddata.io/static/js/bitcoin-business-growth-tab...

99 lines
3.0 KiB
JavaScript

async function fetchDataForTable() {
try {
const dropdown = document.querySelector(".dropdownFilter");
let selectedIndex = dropdown.selectedIndex;
let selectedValue = dropdown.options[selectedIndex].value;
const apiEndpoint =
"https://api.bitlab21.com/bitcoin_business_growth_by_country?latest_date=true";
const response = await fetch(
apiEndpoint + `&cumulative_period_type=${selectedValue}`,
);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const fetchedData = await response.json();
data = fetchedData;
createTable(data);
} catch (error) {
console.error("Fetching data failed:", error);
}
}
function createTable(data) {
const jsonTableContainer = document.getElementById("jsonTableContainer");
jsonTableContainer.innerHTML = "";
const table = document.createElement("table");
let checkedBoxes = [];
const thead = document.createElement("thead");
const headerRow = document.createElement("tr");
tableHeaders = [
"Select",
"Country",
"Previous #",
"Current #",
"Diff",
"% Diff",
];
tableHeaders.forEach((header) => {
const th = document.createElement("th");
th.textContent = header;
headerRow.appendChild(th);
});
thead.appendChild(headerRow);
table.appendChild(thead);
const tbody = document.createElement("tbody");
filteredData = data.filter((item) => 1 === 1);
filteredData.sort((a, b) => {
const sortField = "diff";
return Math.abs(b[sortField]) - Math.abs(a[sortField]);
});
filteredData.forEach((row, index) => {
const tr = document.createElement("tr");
const checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.checked = index < 5; // Check the top 5 rows by default
checkbox.addEventListener("change", function () {
if (this.checked) {
checkedBoxes.push(row["country_name"]);
} else {
checkedBoxes = checkedBoxes.filter((id) => id !== row["country_name"]);
}
});
checkbox.id = row["country_name"];
tr.appendChild(document.createElement("td")).append(checkbox);
columnNames = [
"country_name",
"cumulative_previous_value",
"cumulative_current_value",
"diff",
"pct_diff",
];
columnNames.forEach((columnName) => {
const td = document.createElement("td");
const div = document.createElement("div");
div.id = "scrollable";
div.textContent = row[columnName];
td.appendChild(div);
tr.appendChild(td);
});
tbody.appendChild(tr);
if (checkbox.checked) {
checkedBoxes.push(row["country_name"]);
}
});
table.appendChild(tbody);
const tableContainer = document.getElementById("jsonTableContainer");
tableContainer.appendChild(table);
tableContainer.dispatchEvent(
new CustomEvent("reloadTable", { bubbles: true }),
);
}
window.onload = () => {
const dropdown = document.querySelector(".dropdownFilter");
fetchDataForTable();
dropdown.addEventListener("change", () => {
fetchDataForTable();
});
};