-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
283 lines (257 loc) · 12.6 KB
/
script.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
// to track data is loaded or not
const tabDataLoaded = {
tab1: false,
tab2: false,
tab3: false,
tab4: false,
}
//to open the tab and load the data if it is not loaded yet
const openTab = (event, tabName) => {
const tabContent = document.querySelectorAll(".tab-content")
const tabButtons = document.querySelectorAll(".tab-button")
//hide all tab and remove the active class
tabContent.forEach(content => content.style.display = "none")
tabButtons.forEach(button => button.classList.remove("active"))
//display the content of selected tab and add 'active' class
document.getElementById(tabName).style.display = "block"
event.currentTarget.classList.add("active")
//check the data loaded or not, if not fetch it.
if (!tabDataLoaded[tabName]) {
switch (tabName) {
case 'tab1': fetchAndDisplay('https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=20&page=1&sparkline=true', ['asset-list'], displayAssets, tabName, 'Crypto_Data')
break;
case 'tab2': fetchAndDisplay('https://api.coingecko.com/api/v3/exchanges', ['exchange-list'], displayExchanges, tabName, 'Exchanges_Data')
break;
case 'tab3': fetchAndDisplay('https://api.coingecko.com/api/v3/coins/categories', ['category-list'], displayCategories, tabName, 'Categories_Data')
break
case 'tab4': fetchAndDisplay('https://api.coingecko.com/api/v3/companies/public_treasury/bitcoin', ['company-list'], displayCompanies, tabName, 'Companies_Data')
}
}
}
//run when the page finished loading it will fetch data
document.addEventListener('DOMContentLoaded', () => {
document.querySelector('.tab-button').click(); // to open the 1st tab
fetchData()
})
//fetch the data of trending and asset list
async function fetchData() {
await Promise.all([
fetchAndDisplay('https://api.coingecko.com/api/v3/search/trending', ['coins-list', 'nfts-list'], displayTrend, null, 'Trending_Data'),
fetchAndDisplay('https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=20&page=1&sparkline=true', ['asset-list'], displayAssets, null, 'Crypto_Data')
])
}
//fetch and display from the API
async function fetchAndDisplay(url, idsToToggle, displayFunction, tabName = null, localKey) {
idsToToggle.forEach(id => {
const errorElement = document.getElementById(`${id}-error`)
if (errorElement) { //to hide error message and show spinner
errorElement.style.display = "none"
}
toggleSpinner(id, `${id}-spinner`, true)
})
//get the data from the local storage
const localstorageKey = localKey
const localData = getLocalStorageData(localstorageKey)
//if data is found hide the spinner and show the data
if (localData) {
idsToToggle.forEach(id => toggleSpinner(id, `${id}-spinner`, false))
displayFunction(localData)
}
try { //fetch API if the data is not at local storage
const response = await fetch(url)
if (!response.ok) throw new Error('API limit reached') //throw an error if reponse is not 'ok'
const data = await response.json()
console.log('API Response:', data)
//hide the spinner and show the data
idsToToggle.forEach(id => toggleSpinner(id, `${id}-spinner`, false))
displayFunction(data)
setLocalStorageData(localstorageKey, data) //and save to the local storage
if (tabName) {
tabDataLoaded[tabName] = true
}
} catch (error) { //if there is an error, hide the spinner and show the error message
if (localData) {
displayFunction(localData) //use local data on error
}
idsToToggle.forEach(id => {
toggleSpinner(id, `${id}-spinner`, false)
document.getElementById(`${id}-error`).style.display = 'block'
})
if (tabName) {
tabDataLoaded[tabName] = false //mark the data is not loaded
}
}
}
//display trending data(coins and nfts)
const displayTrend = (data) => {
displayTrendCoins(data.coins.slice(0, 5)) //only top 5
displayTrendNfts(data.nfts.slice(0, 5))
}
//display trending coins
const displayTrendCoins = (coins) => {
const coinsList = document.getElementById('coins-list')
coinsList.innerHTML = '' //clear the current data
const table = createTable(['Coin', 'Price', 'Market Cap', 'Volume', '24h%'])
coins.forEach(coin => {
const coinData = coin.item
const row = document.createElement('tr')
//insert the html into the table row
row.innerHTML = `
<td class="name-column table-fixed-column"><img src="${coinData.thumb}"> ${coinData.name} <span>(${coinData.symbol.toUpperCase()})</span></td>
<td>${parseFloat(coinData.price_btc).toFixed(6)}</td>
<td>${coinData.data.market_cap}</td>
<td>${coinData.data.total_volume}</td>
<td class="${coinData.data.price_change_percentage_24h.usd >= 0 ? 'green' : 'red'}">${coinData.data.price_change_percentage_24h.usd.toFixed(2)}%</td>
`
row.onclick = () => window.location.href = `./coin.html?coin=${coinData.id}` //when click the row it will open the coin.html
table.appendChild(row)
});
coinsList.appendChild(table)
}
//display trending nfts
const displayTrendNfts = (nfts) => {
const nftsList = document.getElementById('nfts-list')
nftsList.innerHTML = '' //clear the current data
const table = createTable(['NFT', 'Market', 'Price', '24h Vol', '24h%'])
nfts.forEach(nft => {
const row = document.createElement('tr')
//insert the html into the table row
row.innerHTML = `
<td class="name-column table-fixed-column"><img src="${nft.thumb}"> ${nft.name} <span>(${nft.symbol.toUpperCase()})</span></td>
<td>${nft.native_currency_symbol.toUpperCase()}</td>
<td>${nft.data.floor_price}</td>
<td>${nft.data.h24_volume}</td>
<td class="${parseFloat(nft.data.floor_price_in_usd_24h_percentage_change) >= 0 ? 'green' : 'red'}">${parseFloat(nft.data.floor_price_in_usd_24h_percentage_change).toFixed(2)}%</td>
`
table.appendChild(row)
});
nftsList.appendChild(table)
}
//display assets
const displayAssets = (data) => {
const cryptoList = document.getElementById('asset-list')
cryptoList.innerHTML = ''
const table = createTable(['Rank', 'Coin', 'Price', '24h Price', '24h Price %', 'Total Vol', 'Market Cap', 'Last 7 Days'], 1)
const sparklineData = []
data.forEach(asset => {
const row = document.createElement('tr')
//insert the html into the table row
row.innerHTML = `
<td class="rank">${asset.market_cap_rank}</td>
<td class="name-column table-fixed-column"><img src="${asset.image}">${asset.name}<span>(${asset.symbol.toUpperCase()})</span></td>
<td>$${asset.current_price.toFixed(2)}</td>
<td class="${asset.price_change_percentage_24h >= 0 ? "green" : "red"}">$${asset.price_change_24h.toFixed(2)}</td>
<td class="${asset.price_change_percentage_24h >= 0 ? "green" : "red"}">${asset.price_change_percentage_24h.toFixed(2)}%</td>
<td>$${asset.total_volume.toLocaleString()}</td>
<td>$${asset.market_cap.toLocaleString()}</td>
<td><canvas id="chart-${asset.id}" width="100" height="50"></canvas></td>
`
table.appendChild(row)
//pushing the sparkline data into the row
sparklineData.push({
id: asset.id,
sparkline: asset.sparkline_in_7d.price,
color: asset.sparkline_in_7d.price[0] <= asset.sparkline_in_7d.price[asset.sparkline_in_7d.price.length - 1] ? 'green' : 'red'
})
row.onclick = () => window.location.href = `./coin.html?coin=${asset.id}`
});
cryptoList.appendChild(table)
//settig up the sparkline chart
sparklineData.forEach(({ id, sparkline, color }) => {
const ctx = document.getElementById(`chart-${id}`).getContext('2d')
new Chart(ctx, {
type: 'line',
data: {
labels: sparkline.map((_, index) => index),
datasets: [{
data: sparkline,
borderColor: color,
fill: false,
pointRadius: 0,
borderWidth: 1
}]
},
options: {
responsive: false,
scales: {
x: {
display: false
},
y: {
display: false
}
},
plugins: {
legend: {
display: false
},
tooltip: {
enabled: false
}
}
}
})
})
}
//displaying the exchange tab
const displayExchanges = (data) => {
const exchangeList = document.getElementById('exchange-list')
exchangeList.innerHTML = '' //clear the current data
const table = createTable(['Rank', 'Exchange', 'Trust Score', '24hr Trade', '24hr Trade (Normal)', 'Country', 'Website', 'Year'])
data = data.slice(0, 20) //only show the first 20
data.forEach(exchange => {
const row = document.createElement('tr')
//insert the html into the table row
row.innerHTML = `
<td class="rank">${exchange.trust_score_rank}</td>
<td class="name-column table-fixed-column"><img src="${exchange.image}">${exchange.name}</td>
<td>${exchange.trust_score}</td>
<td>$${exchange.trade_volume_24h_btc.toLocaleString(undefined, { minimumFractionDigits: 3, maximumFractionDigits: 3 })} (BTC)</td>
<td>$${exchange.trade_volume_24h_btc_normalized.toLocaleString(undefined, { minimumFractionDigits: 3, maximumFractionDigits: 3 })} (BTC)</td>
<td class="name-column">${exchange.country || 'N/A'}</td>
<td class="name-column">${exchange.url}</td>
<td>${exchange.year_established || 'N/A'}</td>
` //to local string is add comma after 3 digit and place only 3 decimals
table.appendChild(row)
});
exchangeList.appendChild(table)
}
//displaying the category tab
const displayCategories = (data) => {
const categoryList = document.getElementById('category-list')
categoryList.innerHTML = '' //clear the current data
const table = createTable(['Top Coins', 'Category', 'Market Cap', '24hr Market Cap', '24hr Volume'])
data = data.slice(0, 20) //only show the first 20
data.forEach(category => {
const row = document.createElement('tr')
//insert the html into the table row
row.innerHTML = `
<td>${category.top_3_coins.map(coin => `<img src="${coin}">`).join('')}</td>
<td class="name-column table-fixed-column">${category.name}</td>
<td>$${category.market_cap ? category.market_cap.toLocaleString(undefined, { minimumFractionDigits: 3, maximumFractionDigits: 3 }) : 'N/A'}</td>
<td class="${category.market_cap_change_24h >= 0 ? 'green' : 'red'}">${category.market_cap_change_24h ? category.market_cap_change_24h.toFixed(3) : '0'}%</td>
<td>$${category.volume_24h ? category.volume_24h.toLocaleString(undefined, { minimumFractionDigits: 3, maximumFractionDigits: 3 }) : 'N/A'}</td>
`
table.appendChild(row)
});
categoryList.appendChild(table)
}
//display the company tab
const displayCompanies = (data) => {
const companyList = document.getElementById("company-list")
companyList.innerHTML = '' //clear the current data
const table = createTable(['Company', 'Total BTC', 'Entry Value', 'Total Current Value', 'Total %'])
data.companies.forEach(company => {
const row = document.createElement('tr')
//insert the html into the table row
row.innerHTML = `
<td class="name-column table-fixed-column">${company.name}</td>
<td>${company.total_holdings}</td>
<td>$${company.total_entry_value_usd}</td>
<td>$${company.total_current_value_usd}</td>
<td class="${company.percentage_of_total_supply >= 0 ? 'green' : 'red'}">${company.percentage_of_total_supply}%</td>
`
table.appendChild(row)
});
companyList.appendChild(table)
}