-
Notifications
You must be signed in to change notification settings - Fork 0
/
global.js
200 lines (170 loc) · 7.46 KB
/
global.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
const coinsCount = document.getElementById('coins-count')
const exchangeCount = document.getElementById('exchanges-count')
const marketCap = document.getElementById('marketCap')
const marketCapChangeElement = document.getElementById('marketCapChange')
const volume = document.getElementById('volume')
const dominance = document.getElementById('dominance')
//when the HTML content fully loaded then fetch the data
document.addEventListener("DOMContentLoaded", () => {
//adding theme toggle
const themeToggle = document.getElementById('theme-toggle')
const body = document.body
const savedTheme = localStorage.getItem('theme') //get the saved theme from the local storage
if (savedTheme) {
body.id = savedTheme
updateIcon(savedTheme) //update icon based on the saved theme
}
//check current theme and switch to its opposite theme
themeToggle.addEventListener('click', () => {
if (body.id === 'light-theme') {
body.id = 'dark-theme'
localStorage.setItem('theme', 'dark-theme')
updateIcon('dark-theme')
} else {
body.id = 'light-theme'
localStorage.setItem('theme', 'light-theme')
updateIcon('light-theme')
}
if (typeof initializeWidget === 'function') {
initializeWidget()
}
})
//update icon based on the theme
function updateIcon(currentTheme) {
if (currentTheme === 'light-theme') {
themeToggle.classList.remove('ri-moon-line')
themeToggle.classList.add('ri-sun-line')
} else {
themeToggle.classList.add('ri-moon-line')
themeToggle.classList.remove('ri-sun-line')
}
}
//handling form submission
const form = document.getElementById('searchForm')
form.addEventListener('submit', (event) => {
event.preventDefault()
const query = document.getElementById('searchInput').value.trim()
if (!query) return //if input is empty do nothing
window.location.href = `./search.html?query=${query}`
})
fetchGlobal();
})
//Read the data from localstorage
const getLocalStorageData = (key) => {
const storedData = localStorage.getItem(key)
if (!storedData) return null //null if there is no data
const parsedData = JSON.parse(storedData)
const currentTime = Date.now()
//if the data is older than 5min the data remove and fetch again
if (currentTime - parsedData.timestamp > 300000) {
localStorage.removeItem(key)
return null
}
return parsedData.data
}
//store the data in local storage with a timestamp
const setLocalStorageData = (key, data) => {
const storedData = {
timestamp: Date.now(),
data: data
}
localStorage.setItem(key, JSON.stringify(storedData)) //save the data in local storage
}
//fetch the global cryptocurrency data from "CoinGecko API"
const fetchGlobal = () => {
const localStorageKey = 'Global_Data' //define the key
const localData = getLocalStorageData(localStorageKey)
//if data is found display it, if not fetch new data
if (localData) {
displayGlobalData(localData)
} else {
const options = { method: 'GET', headers: { accept: 'application/json' } };
fetch('https://api.coingecko.com/api/v3/global', options)
.then(response => response.json())
.then(data => {
const globalData = data.data //extract the data from API response
displayGlobalData(globalData)
setLocalStorageData(localStorageKey, globalData) //and save to local storage
})
.catch(error => { //if any error show not available
coinsCount.textContent = 'N/A'
exchangeCount.textContent = 'N/A'
marketCap.textContent = 'N/A'
marketCapChangeElement.textContent = 'N/A'
volume.textContent = 'N/A'
dominance.textContent = 'BTC N/A% - ETH N/A%'
console.error(error)
})
}
}
//display the data in the HTML element
const displayGlobalData = (globalData) => {
console.log(globalData)
//coin and exchange count
coinsCount.textContent = globalData.active_cryptocurrencies || "N/A"
exchangeCount.textContent = globalData.markets || "N/A"
//market cap and its change in % if its above 0 then green and below red
marketCap.textContent = globalData.total_market_cap?.usd ? `$${(globalData.total_market_cap.usd / 1e12).toFixed(3)}T` : "N/A"
const marketCapChange = globalData.market_cap_change_percentage_24h_usd
if (marketCapChange !== undefined) {
const changeText = `${marketCapChange.toFixed(1)}%` // "toFixed" used to fix decimal place here it shows only 1 decimal place
marketCapChangeElement.innerHTML = `${changeText} <i class="${marketCapChange < 0 ? 'red' : 'green'} ri-arrow-${marketCapChange < 0 ? 'down' : 'up'}-s-fill"></i>`
marketCapChangeElement.style.color = marketCapChange < 0 ? 'red' : 'green'
} else {
marketCapChangeElement.textContent = "N/A"
}
// "total_volume?usd" this means if there is total volume exist then access to the usd from total volume.
volume.textContent = globalData.total_volume?.usd ? `$${(globalData.total_volume.usd / 1e9).toFixed(3)}B` : 'N/A'
//adding BTC and ETH dominance
const btcDominance = globalData.market_cap_percentage?.btc ? `${globalData.market_cap_percentage.btc.toFixed(1)}%` : 'N/A'
const ethDominance = globalData.market_cap_percentage?.eth ? `${globalData.market_cap_percentage.eth.toFixed(1)}%` : 'N/A'
dominance.textContent = `BTC ${btcDominance} - ETH ${ethDominance}`
}
//function to toggle the list and spinner based on show
const toggleSpinner = (listId, spinnerId, show) => {
const listElement = document.getElementById(listId)
const spinnerElement = document.getElementById(spinnerId)
if (spinnerElement) {
spinnerElement.style.display = show ? 'block' : 'none'
}
if (listElement) {
listElement.style.display = show ? 'none' : 'block'
}
}
//create a HTML table with header
const createTable = (headers, fixedIndex = 0) => {
const table = document.createElement('table')
const thead = document.createElement('thead')
table.appendChild(thead)
const headerRow = document.createElement('tr') //create a row for the header
headers.forEach((header, index) => { //add each header to the row
const th = document.createElement('th')
th.textContent = header
if (index === fixedIndex) {
th.classList.add('table-fixed-column')
}
headerRow.appendChild(th) //add header cell to the row
});
thead.appendChild(headerRow) // add row to the table
return table
}
//creating the trading view widget
const createWidget = (containerId, widgetConfig, widgetSrc) => {
const container = document.getElementById(containerId)
container.innerHTML = ''
const widgetDiv = document.createElement('div')
widgetDiv.classList.add('tradingview-widget-container__widget')
container.appendChild(widgetDiv)
const script = document.createElement('script')
script.type = 'text/javascript'
script.src = widgetSrc
script.async = true
script.innerHTML = JSON.stringify(widgetConfig)
container.appendChild(script)
setTimeout(() => {
const copyright = document.querySelector('.tradingview-widget-copyright')
if (copyright) {
copyright.classList.remove('hidden')
}
}, 5000)
}