Spaces:
Running
Running
Create script.js
Browse files
script.js
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
async function convertCurrency() {
|
| 2 |
+
const amount = document.getElementById('amount').value;
|
| 3 |
+
const fromCurrency = document.getElementById('from-currency').value;
|
| 4 |
+
const toCurrency = document.getElementById('to-currency').value;
|
| 5 |
+
const result = document.getElementById('result');
|
| 6 |
+
const convertBtn = document.getElementById('convert-btn');
|
| 7 |
+
|
| 8 |
+
if (amount && fromCurrency && toCurrency) {
|
| 9 |
+
try {
|
| 10 |
+
const response = await fetch(`https://api.exchangerate-api.com/v4/latest/${fromCurrency}`);
|
| 11 |
+
const data = await response.json();
|
| 12 |
+
const rate = data.rates[toCurrency];
|
| 13 |
+
const convertedAmount = (amount * rate).toFixed(2);
|
| 14 |
+
|
| 15 |
+
// Display conversion result
|
| 16 |
+
result.innerHTML = `${amount} ${fromCurrency} = ${convertedAmount} ${toCurrency}`;
|
| 17 |
+
|
| 18 |
+
// Hide convert button after conversion
|
| 19 |
+
convertBtn.style.display = 'none';
|
| 20 |
+
} catch (error) {
|
| 21 |
+
result.innerText = "Error fetching exchange rates!";
|
| 22 |
+
}
|
| 23 |
+
}
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
function swapCurrencies() {
|
| 27 |
+
const fromCurrency = document.getElementById('from-currency');
|
| 28 |
+
const toCurrency = document.getElementById('to-currency');
|
| 29 |
+
|
| 30 |
+
// Swap currency values
|
| 31 |
+
const temp = fromCurrency.value;
|
| 32 |
+
fromCurrency.value = toCurrency.value;
|
| 33 |
+
toCurrency.value = temp;
|
| 34 |
+
|
| 35 |
+
// Automatically convert after swap
|
| 36 |
+
convertCurrency();
|
| 37 |
+
}
|
| 38 |
+
|
| 39 |
+
// Event listeners for input and currency change
|
| 40 |
+
document.getElementById('amount').addEventListener('input', convertCurrency);
|
| 41 |
+
|
| 42 |
+
document.getElementById('from-currency').addEventListener('change', () => {
|
| 43 |
+
document.getElementById('convert-btn').style.display = 'block';
|
| 44 |
+
document.getElementById('result').innerHTML = '';
|
| 45 |
+
});
|
| 46 |
+
|
| 47 |
+
document.getElementById('to-currency').addEventListener('change', () => {
|
| 48 |
+
document.getElementById('convert-btn').style.display = 'block';
|
| 49 |
+
document.getElementById('result').innerHTML = '';
|
| 50 |
+
});
|