Currency Converter
Currency Converter
body {
font-family: Arial, sans-serif;
background-color: #f0f0f0;
color: #333;
margin: 0;
padding: 0;
}
.container {
max-width: 600px;
margin: 2rem auto;
padding: 1rem;
background-color: #fff;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
h1 {
text-align: center;
color: #333;
margin-bottom: 1rem;
}
.converter {
display: flex;
flex-direction: column;
}
.input-group, .currency-group {
margin-bottom: 1rem;
}
label {
display: block;
margin-bottom: 0.5rem;
color: #555;
}
input, select, button {
width: 100%;
padding: 0.75rem;
border: 1px solid #ddd;
border-radius: 4px;
}
input:focus, select:focus, button:focus {
outline: none;
border-color: #007bff;
}
button {
background-color: #007bff;
color: #fff;
border: none;
cursor: pointer;
}
button:hover {
background-color: #0056b3;
}
.result {
margin-top: 1rem;
font-size: 1.2rem;
color: #333;
}
document.addEventListener('DOMContentLoaded', () => {
const fromCurrencySelect = document.getElementById('from-currency');
const toCurrencySelect = document.getElementById('to-currency');
const amountInput = document.getElementById('amount');
const convertBtn = document.getElementById('convert-btn');
const convertedAmount = document.getElementById('converted-amount');
const apiURL = 'https://api.exchangerate-api.com/v4/latest/USD';
let exchangeRates = {};
// Fetch currency data
fetch(apiURL)
.then(response => response.json())
.then(data => {
exchangeRates = data.rates;
populateCurrencySelects();
})
.catch(error => console.error('Error fetching currency data:', error));
// Populate currency select elements
function populateCurrencySelects() {
const currencies = Object.keys(exchangeRates);
const options = currencies.map(currency => `
`).join('');
fromCurrencySelect.innerHTML = options;
toCurrencySelect.innerHTML = options;
}
// Convert currency
convertBtn.addEventListener('click', () => {
const amount = parseFloat(amountInput.value);
const fromCurrency = fromCurrencySelect.value;
const toCurrency = toCurrencySelect.value;
if (!amount || isNaN(amount) || fromCurrency === toCurrency) {
convertedAmount.textContent = 'Please enter a valid amount and select different currencies.';
return;
}
const rateFrom = exchangeRates[fromCurrency];
const rateTo = exchangeRates[toCurrency];
const converted = (amount / rateFrom) * rateTo;
convertedAmount.textContent = `Converted Amount: ${converted.toFixed(2)} ${toCurrency}`;
});
});
No comments:
Post a Comment