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
49 lines (38 loc) · 1.42 KB
/
lecture-exercises.js
File metadata and controls
49 lines (38 loc) · 1.42 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
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 (){
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);