forked from icaroharry/cambio-da-casa-do-milho
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
89 lines (71 loc) · 2.07 KB
/
script.js
File metadata and controls
89 lines (71 loc) · 2.07 KB
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
const apiInfo = {
api: 'https://api.ratesapi.io/api/',
endpoint: 'latest'
}
const url = `${apiInfo.api}${apiInfo.endpoint}`
window.onload = () => {
setupEventHandlers();
}
const setupEventHandlers = () => {
const searchButton = document.querySelector('#search-button');
searchButton.addEventListener('click', handleSearchEvent);
const inputText = document.querySelector('#currency-input');
inputText.addEventListener('keyup', (event) => {
if (event.keyCode === 13) {
handleSearchEvent();
}
});
}
const handleSearchEvent = () => {
const currencyValue = document.querySelector('#currency-input').value;
if (currencyValue === '') {
renderEmptyAlert()
} else {
clearList();
fetchCurrency(currencyValue);
}
}
const renderEmptyAlert = () => {
window.alert('Por favor, insira alguma moeda!');
}
const clearList = () => {
const currencyList = document.querySelector('#currency-list');
currencyList.innerHTML = '';
}
const fetchCurrency = (currency) => {
const endpoint = `${url}?base=${currency}`;
fetch(endpoint)
.then((response) => response.json())
.then((object) => {
console.log(object);
if (object.error) {
throw new Error(object.error);
} else {
handleRates(object.rates);
}
})
.catch((error) => handleError(error))
}
const handleError = (errorMessage) => {
window.alert(errorMessage);
}
const handleRates = (rates) => {
const ratesKeys = Object.keys(rates);
ratesKeys.forEach((key) => {
const value = rates[key];
renderRate(key, value);
})
}
const renderRate = (key, value) => {
const currencyList = document.querySelector('#currency-list');
const formattedValue = value.toFixed(2);
const li = document.createElement('li');
li.innerHTML = `<b>${key}:</b> ${formattedValue} <img src="./assets/trash.png">`;
li.addEventListener('click', handleItemListClick);
currencyList.appendChild(li);
}
const handleItemListClick = (event) => {
const currencyList = document.querySelector('#currency-list');
const li = event.target;
currencyList.removeChild(li);
}