forked from HackYourFuture/JavaScript2
-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathlecture-exercises.js
More file actions
45 lines (40 loc) · 1.47 KB
/
lecture-exercises.js
File metadata and controls
45 lines (40 loc) · 1.47 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
async function getRandomAdvice() {
const adviceReq = fetch('https://api.adviceslip.com/advice'); // send request
const adviceResponse = await adviceReq; // wait until something comes back
// const jsonString = await adviceResponse.text();
// return jsonString
// const adviceData = JSON.parse(jsonString)
// return jsonString
const adviceData = await adviceResponse.json(); // parses JSON string into native JavaScript object
return adviceData.slip.advice;
}
let allAdvice = [];
const adviceEl = document.getElementById('advice');
function updateDom() {
adviceEl.innerHTML = '';
allAdvice.forEach((advice, index) => {
const adviceItem = document.createElement('li');
adviceEl.appendChild(adviceItem);
adviceItem.innerText = advice;
const removeButton = document.createElement('button');
removeButton.innerText = 'Remove';
adviceItem.appendChild(removeButton);
removeButton.addEventListener('click', () => deleteAdvice(index));
});
}
function deleteAdvice(index) {
allAdvice.splice(index, 1);
updateDom();
}
function upcaseAllAdvice() {
// eslint-disable-next-line no-const-assign
allAdvice = allAdvice.map(advice => advice.toUpperCase());
updateDom();
}
async function setRandomAdvice() {
allAdvice.push(await getRandomAdvice());
updateDom();
}
setRandomAdvice();
document.getElementById('add-advice').addEventListener('click', setRandomAdvice);
document.getElementById('upcase-everything').addEventListener('click', upcaseAllAdvice);