Pages

Thursday, 19 December 2024

Currency Converter Tool

>br>
Currency Converter

Currency Converter

body { font-family: Arial, sans-serif; background: linear-gradient(to right, #00c6ff, #0072ff); color: #fff; margin: 0; padding: 0; display: flex; justify-content: center; align-items: center; height: 100vh; } .currency-converter { background: #ffffff10; border-radius: 12px; padding: 20px; width: 90%; max-width: 400px; text-align: center; box-shadow: 0 8px 15px rgba(0, 0, 0, 0.1); } h1 { margin-bottom: 20px; } .input-group { margin-bottom: 15px; text-align: left; } label { display: block; font-weight: bold; margin-bottom: 5px; } input, select { width: 100%; padding: 10px; border: 1px solid #ccc; border-radius: 5px; outline: none; } button { background: #0072ff; color: white; padding: 10px 20px; border: none; border-radius: 5px; cursor: pointer; transition: background 0.3s; } button:hover { background: #005bb5; } .result { margin-top: 20px; font-size: 1.2em; font-weight: bold; } const apiURL = "https://api.exchangerate-api.com/v4/latest/"; document.addEventListener("DOMContentLoaded", () => { const fromCurrency = document.getElementById("from-currency"); const toCurrency = document.getElementById("to-currency"); const convertBtn = document.getElementById("convert-btn"); const amountInput = document.getElementById("amount"); const resultDiv = document.getElementById("result"); // Fetch all currency rates fetch(`${apiURL}USD`) .then((response) => response.json()) .then((data) => { const currencies = Object.keys(data.rates); populateSelectOptions(currencies, fromCurrency); populateSelectOptions(currencies, toCurrency); fromCurrency.value = "USD"; toCurrency.value = "EUR"; }); // Populate dropdown options function populateSelectOptions(currencies, selectElement) { currencies.forEach((currency) => { const option = document.createElement("option"); option.value = currency; option.textContent = currency; selectElement.appendChild(option); }); } // Handle conversion convertBtn.addEventListener("click", () => { const amount = parseFloat(amountInput.value); const from = fromCurrency.value; const to = toCurrency.value; if (isNaN(amount) || amount <= 0) { resultDiv.textContent = "Please enter a valid amount."; return; } fetch(`${apiURL}${from}`) .then((response) => response.json()) .then((data) => { const rate = data.rates[to]; const convertedAmount = (amount * rate).toFixed(2); resultDiv.textContent = `${amount} ${from} = ${convertedAmount} ${to}`; }) .catch(() => { resultDiv.textContent = "Error fetching conversion rates."; }); }); });