본문 바로가기
JavaScript

[JavaScript] CoinGecko API 와 chart api를 사용하여 각 화폐의 현재 USD 가격 표 형태로 비교하기

by teamnova 2024. 4. 6.

안녕하세요 오늘은 CoinGecko API 와 chart api를 사용하여 각 화폐의 현재 USD 가격 표 형태로 비교해보겠습니다.

 

index.html 파일에 다음과 같이 코드를 작성해주세요

<!DOCTYPE html>
<html lang="en">
<head>
    <!-- 기본 HTML 헤드 설정 -->
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Crypto Price Comparison</title>
    <!-- Tailwind CSS 연결 -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- JavaScript 파일 연결 -->
    <script defer src="script.js"></script>
</head>
<body class="bg-gray-100 flex justify-center items-center h-screen">
    <div class="container">
        <h1 class="text-xl font-bold mb-4">Crypto Price Comparison</h1>
        <!-- 여러 가상 화폐를 선택할 수 있는 멀티 셀렉트 박스 -->
        <select id="crypto-multi-select" class="border p-2 rounded" multiple>
            <option value="bitcoin">Bitcoin</option>
            <option value="ethereum">Ethereum</option>
            <option value="litecoin">Litecoin</option>
            <!-- 추가로 다른 가상 화폐 옵션 추가 가능 -->
        </select>
        <!-- 가격 비교 버튼 -->
        <button id="compare-prices" class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded ml-2">
            Compare Prices
        </button>
        <!-- 가격 표시 표 -->
        <table id="prices-table" class="table-auto border-collapse border border-gray-400 mt-4">
            <thead>
                <tr>
                    <th class="border border-gray-300">Cryptocurrency</th>
                    <th class="border border-gray-300">Price (USD)</th>
                </tr>
            </thead>
            <tbody id="prices-tbody">
                <!-- 여기에 가격 데이터가 표시됩니다 -->
            </tbody>
        </table>
    </div>
</body>
</html>

 

 

 

script.js 파일에 다음과 같이 코드를 작성해주세요

document.getElementById('compare-prices').addEventListener('click', async () => {
  const selectedCryptos = Array.from(document.getElementById('crypto-multi-select').selectedOptions).map(option => option.value);
  const tbody = document.getElementById('prices-tbody');

  try {
    // 선택된 모든 가상 화폐에 대한 가격 정보 요청
    const promises = selectedCryptos.map(crypto =>
      fetch(`https://api.coingecko.com/api/v3/simple/price?ids=${crypto}&vs_currencies=usd`)
        .then(response => response.json())
    );

    const results = await Promise.all(promises);

    // 테이블에 가격 정보 채우기
    tbody.innerHTML = results.map((result, index) => {
      const crypto = selectedCryptos[index];
      const price = result[crypto].usd;
      return `<tr><td class="border border-gray-300">${crypto}</td><td class="border border-gray-300">${price}</td></tr>`;
    }).join('');
  } catch (error) {
    console.error('Error fetching prices:', error);
  }
});

 

 

그러면 다음과 같은 결과물을 얻을 수 있습니다.