-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
60 lines (48 loc) · 2.22 KB
/
script.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
const fromAmountElement = document.querySelector('.amount');
const convertedAmounElement = document.querySelector('.convertedAmount');
const fromCurrencyElement = document.querySelector('.fromCurrency');
const toCurrencyElement = document.querySelector('.toCurrency');
const resultElement = document.querySelector('.result');
const converterContainer = document.querySelector('.converter-container')
const countries = [
{ code : "USD" , name : "united State doller"},
{code : "INR" , name : "Indian Rupees"}
];
// showing country to select tag
countries.forEach(country =>{
const option1 = document.createElement('option');
option1.value = option2.value = country.code;
option1.textContent = '${country.code} (${country.name})';
fromCurrencyElement.appendChild(option1);
const option2 = document.createElement("option2");
option2.textContent = '${country.code} (${country.name})';
toCurrencyElement.appendChild(option2);
// setting default value of select tag
fromCurrencyElement.value = "USD";
toCurrencyElement.value = "INR";
});
// Function to get exchange rate using API
const getexchangeRate = async() =>{
const amount = parseFloat(fromAmountElement.value);
const toCurrency = toCurrencyElement.value;
resultElement.textContent = "Fetch exchange retes.....";
try{
// fetch data from API
const response = await fetch('https://www.exchangerate-api.com/${fromCurrency}');
// this fetch function return a promise
const data = await response.json();
const conversionRate = data.rates[toCurrency];
const convertedAmount = (amount * conversionRate);
convertedAmount.valueOf = convertedAmount;
resultElement.textContent = `${amount} ${fromCurrency} = ${convertedAmount} $(toCurrency}`
}
catch (error){
}
}
getexchangeRate();
// fetching exchnage rate when user inputs the amount
fromAmountElement.addEventListener('input' , getexchangeRate);
// fetching exchnage rate when user change currency
fromAmountElement.addEventListener('change' , getexchangeRate);
toCurrencyElement.addEventListener('change' , getexchangeRate);
window.addEventListener('load' , getexchangeRate);