-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathfetch-api-get-json.html
69 lines (66 loc) · 1.72 KB
/
fetch-api-get-json.html
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Fetch Api With Json</title>
<link
href="https://fonts.googleapis.com/css2?family=Roboto:wght@100;400&display=swap"
rel="stylesheet"
/>
<style>
body {
font-family: "Roboto", sans-serif;
}
h1 {
text-align: center;
}
button {
display: block;
margin: 20px auto;
border: none;
border-radius: none;
font-size: 20px;
}
.quote {
border: solid 1px black;
padding: 10px;
margin: 10px;
}
#error {
text-align: center;
color: red;
display: none;
}
</style>
</head>
<body>
<h1>Famous Quotes</h1>
<section id="quotes"></section>
<p id="error">There was an error fetching the request.</p>
<script>
const quotesEl = document.querySelector("#quotes");
const errorEl = document.querySelector("#error");
function addQuote(quote, index) {
if (index > 10) {
return;
}
const quoteEl = document.createElement("article");
quoteEl.classList.add("quote");
quoteEl.textContent = quote.text;
quotesEl.appendChild(quoteEl);
}
async function getQuotes() {
try {
const response = await fetch("https://type.fit/api/quotes");
const quotes = await response.json();
quotes.forEach(addQuote);
} catch (e) {
errorEl.style.display = "block";
console.error(e);
}
}
document.addEventListener("DOMContentLoaded", getQuotes);
</script>
</body>
</html>