Let’s create a simple Crypto Tracker using client-side JavaScript that fetches cryptocurrency data from a public API and displays it in a web page. We’ll use the CoinGecko API for this purpose.
Step-by-Step Guide
- Create the HTML structure
- Write the JavaScript code to fetch and display the data
Step 1: HTML Structure
Create an index.html
file with the following content:
html<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Crypto Tracker</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
}
table {
width: 100%;
border-collapse: collapse;
}
th, td {
padding: 12px;
text-align: left;
border-bottom: 1px solid #ddd;
}
th {
background-color: #f4f4f4;
}
</style>
</head>
<body>
<h1>Crypto Tracker</h1>
<table>
<thead>
<tr>
<th>Name</th>
<th>Symbol</th>
<th>Current Price (USD)</th>
<th>Market Cap (USD)</th>
<th>24h Change</th>
</tr>
</thead>
<tbody id="crypto-data">
<!-- Data will be injected here by JavaScript -->
</tbody>
</table>
<script>
async function fetchCryptoData() {
try {
const response = await fetch('https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd');
const data = await response.json();
return data;
} catch (error) {
console.error('Error fetching crypto data:', error);
return [];
}
}
function displayCryptoData(data) {
const tableBody = document.getElementById('crypto-data');
tableBody.innerHTML = ''; // Clear any existing data
data.forEach(coin => {
const row = document.createElement('tr');
const nameCell = document.createElement('td');
nameCell.textContent = coin.name;
row.appendChild(nameCell);
const symbolCell = document.createElement('td');
symbolCell.textContent = coin.symbol.toUpperCase();
row.appendChild(symbolCell);
const priceCell = document.createElement('td');
priceCell.textContent = `$${coin.current_price.toLocaleString()}`;
row.appendChild(priceCell);
const marketCapCell = document.createElement('td');
marketCapCell.textContent = `$${coin.market_cap.toLocaleString()}`;
row.appendChild(marketCapCell);
const changeCell = document.createElement('td');
changeCell.textContent = `${coin.price_change_percentage_24h.toFixed(2)}%`;
changeCell.style.color = coin.price_change_percentage_24h >= 0 ? 'green' : 'red';
row.appendChild(changeCell);
tableBody.appendChild(row);
});
}
async function main() {
const cryptoData = await fetchCryptoData();
displayCryptoData(cryptoData);
}
main();
</script>
</body>
</html>
Explanation
- HTML Structure:
- We have a simple HTML page with a table to display the cryptocurrency data.
- The table has headers for the name, symbol, current price, market cap, and 24-hour change.
- JavaScript Code:
fetchCryptoData
: This function fetches data from the CoinGecko API. It uses thefetch
API to make an HTTP GET request to the CoinGecko API endpoint that returns market data for various cryptocurrencies.displayCryptoData
: This function takes the data fetched from the API and dynamically creates table rows (<tr>
) and cells (<td>
) for each cryptocurrency. It appends these rows to the table body (<tbody>
).main
: This is the main function that coordinates the fetching and displaying of data. It callsfetchCryptoData
to get the data and thendisplayCryptoData
to display it on the web page.
Running the Application
- Save the HTML code to a file named
index.html
. - Open this file in a web browser.
You should see a table displaying real-time data for various cryptocurrencies fetched from the CoinGecko API. The table will show the name, symbol, current price, market cap, and 24-hour price change for each cryptocurrency.
This is a basic implementation of a crypto tracker. You can enhance it further by adding features such as auto-refreshing the data at regular intervals, sorting and filtering options, or displaying additional details for each cryptocurrency.
Leave a Reply