-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscripts.js
77 lines (69 loc) · 2.01 KB
/
scripts.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
const fetchAllButton = document.getElementById('fetch-quotes');
const fetchRandomButton = document.getElementById('fetch-random');
const fetchByAuthorButton = document.getElementById('fetch-by-author');
const quoteContainer = document.getElementById('quote-container');
const quoteText = document.querySelector('.quote');
const attributionText = document.querySelector('.attribution');
const resetQuotes = () => {
quoteContainer.innerHTML = '';
}
const renderError = response => {
quoteContainer.innerHTML = `<p>Your request returned an error from the server: </p>
<p>Code: ${response.status}</p>
<p>${response.statusText}</p>`;
}
const renderQuotes = (quotes = []) => {
resetQuotes();
if (quotes.length > 0) {
quotes.forEach(quote => {
const newQuote = document.createElement('div');
newQuote.className = 'single-quote';
newQuote.innerHTML = `<div class="quote-text">${quote.quote}</div>
<div class="attribution">- ${quote.person}</div>`;
quoteContainer.appendChild(newQuote);
});
} else {
quoteContainer.innerHTML = '<p>Your request returned no quotes.</p>';
}
}
app.use(express.static('public'));
fetchAllButton.addEventListener('click', () => {
fetch('/api/quotes')
.then(response => {
if (response.ok) {
return response.json();
} else {
renderError(response);
}
})
.then(response => {
renderQuotes(response.quotes);
});
});
fetchRandomButton.addEventListener('click', () => {
fetch('/api/quotes/random')
.then(response => {
if (response.ok) {
return response.json();
} else {
renderError(response);
}
})
.then(response => {
renderQuotes([response.quote]);
});
});
fetchByAuthorButton.addEventListener('click', () => {
const author = document.getElementById('author').value;
fetch(`/api/quotes?person=${author}`)
.then(response => {
if (response.ok) {
return response.json();
} else {
renderError(response);
}
})
.then(response => {
renderQuotes(response.quotes);
});
});