Currency Converter
Currency Converter
body {
font-family: Arial, sans-serif;
background-color: #f9f9f9;
margin: 0;
padding: 0;
}
.container {
max-width: 600px;
margin: 0 auto;
padding: 20px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
background-color: #ffffff;
}
h1 {
text-align: center;
color: #4CAF50;
}
.input-wrapper {
display: flex;
margin-bottom: 10px;
}
label {
flex: 1;
}
input[type="number"] {
flex: 2;
padding: 10px;
margin-right: 10px;
border: 1px solid #ccc;
border-radius: 4px;
}
select {
flex: 2;
padding: 10px;
margin-right: 10px;
border: 1px solid #ccc;
border-radius: 4px;
}
button {
background-color: #4CAF50;
color: #ffffff;
border: none;
padding: 10px 20px;
cursor: pointer;
border-radius: 4px;
width: 100%;
}
button:hover {
background-color: #45a049;
}
.result {
margin-top: 20px;
padding: 10px;
background-color: #f2f2f2;
border-radius: 4px;
display: none;
}
.result p {
margin: 0;
color: #333;
}
#convertedAmount {
font-weight: bold;
color: #333;
}
const fromCurrencySelect = document.getElementById('fromCurrency');
const toCurrencySelect = document.getElementById('toCurrency');
const amountInput = document.getElementById('amount');
const convertButton = document.getElementById('convertButton');
const convertedAmountElement = document.getElementById('convertedAmount');
const resultDiv = document.getElementById('result');
// Fetch list of currencies and populate dropdowns
fetch('https://api.exchangerate-api.com/v4/latest/USD')
.then(response => response.json())
.then(data => {
const currencies = Object.keys(data.rates);
populateDropdowns(currencies);
})
.catch(error => {
console.error('Error fetching currency data:', error);
});
function populateDropdowns(currencies) {
for (const currency of currencies) {
const option1 = document.createElement('option');
option1.value = currency;
option1.textContent = currency;
fromCurrencySelect.appendChild(option1);
const option2 = document.createElement('option');
option2.value = currency;
option2.textContent = currency;
toCurrencySelect.appendChild(option2);
}
}
convertButton.addEventListener('click', convertCurrency);
function convertCurrency() {
const fromCurrency = fromCurrencySelect.value;
const toCurrency = toCurrencySelect.value;
const amount = parseFloat(amountInput.value);
if (isNaN(amount)) {
alert('Please enter a valid numeric amount.');
return;
}
fetch(`https://api.exchangerate-api.com/v4/latest/${fromCurrency}`)
.then(response => response.json())
.then(data => {
const rate = data.rates[toCurrency];
const convertedAmount = amount * rate;
showResult(convertedAmount, toCurrency);
})
.catch(error => {
console.error('Error fetching exchange rate data:', error);
});
}
function showResult(convertedAmount, toCurrency) {
convertedAmountElement.textContent = `Converted Amount: ${convertedAmount.toFixed(2)} ${toCurrency}`;
resultDiv.style.display = 'block';
}
0 Comments