-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathscript.js
59 lines (30 loc) · 1.45 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
const currencyElement_one = document.getElementById('currency-one')
const currencyElement_two = document.getElementById('currency-two')
const amountElement_one = document.getElementById('amount-one')
const amountElement_two = document.getElementById('amount-two')
const rateElement = document.getElementById('rate')
const swap = document.getElementById('swap')
// fetch exchange rates + DOM updates
const calculate = (()=>{
const currency_one = currencyElement_one.value
const currency_two = currencyElement_two.value
fetch(`https://api.exchangerate-api.com/v4/latest/${currency_one}`)
.then(res=> res.json())
.then(data => {
const rate = data.rates[currency_two]; //providing the index for the rate
rateElement.innerText = `1 ${currency_one} = ${rate} ${currency_two}`
amountElement_two.value = (amountElement_one.value * rate).toFixed(2) //2 deciaml pts
})
})
// event listeners
currencyElement_one.addEventListener("change", calculate)
amountElement_one.addEventListener("input", calculate)
currencyElement_two.addEventListener("change", calculate)
amountElement_one.addEventListener("input", calculate)
swap.addEventListener('click', ()=>{
const temp = currencyElement_one.value
currencyElement_one.value = currencyElement_two.value
currencyElement_two.value = temp
calculate()
})
calculate()