-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
62 lines (56 loc) · 2.23 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
61
62
const dropList = document.querySelectorAll("form select"),
fromCurrency = document.querySelector(".from select"),
toCurrency = document.querySelector(".to select"),
getButton = document.querySelector("form button");
for (let i = 0; i < dropList.length; i++) {
for(let currency_code in country_list){
let selected = i == 0 ? currency_code == "USD" ? "selected" : "" : currency_code == "INR" ? "selected" : "";
let optionTag = `<option value="${currency_code}" ${selected}>${currency_code}</option>`;
dropList[i].insertAdjacentHTML("beforeend", optionTag);
}
dropList[i].addEventListener("change", e =>{
loadFlag(e.target);
});
}
function loadFlag(element){
for(let code in country_list){
if(code == element.value){
let imgTag = element.parentElement.querySelector("img");
imgTag.src = `https://flagcdn.com/48x36/${country_list[code].toLowerCase()}.png`;
}
}
}
window.addEventListener("load", ()=>{
getExchangeRate();
});
getButton.addEventListener("click", e =>{
e.preventDefault();
getExchangeRate();
});
const exchangeIcon = document.querySelector("form .icon");
exchangeIcon.addEventListener("click", ()=>{
let tempCode = fromCurrency.value;
fromCurrency.value = toCurrency.value;
toCurrency.value = tempCode;
loadFlag(fromCurrency);
loadFlag(toCurrency);
getExchangeRate();
})
function getExchangeRate(){
const amount = document.querySelector("form input");
const exchangeRateTxt = document.querySelector("form .exchange-rate");
let amountVal = amount.value;
if(amountVal == "" || amountVal == "0"){
amount.value = "1";
amountVal = 1;
}
exchangeRateTxt.innerText = "Getting exchange rate...";
let url = `https://v6.exchangerate-api.com/v6/ea77b0361a1aeb7467ed05d1/latest/${fromCurrency.value}`;
fetch(url).then(response => response.json()).then(result =>{
let exchangeRate = result.conversion_rates[toCurrency.value];
let totalExRate = (amountVal * exchangeRate).toFixed(2);
exchangeRateTxt.innerText = `${amountVal} ${fromCurrency.value} = ${totalExRate} ${toCurrency.value}`;
}).catch(() =>{
exchangeRateTxt.innerText = "Something went wrong";
});
}