-
Notifications
You must be signed in to change notification settings - Fork 0
/
02-random-ron-no-duplicates.html
75 lines (60 loc) · 1.74 KB
/
02-random-ron-no-duplicates.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
70
71
72
73
74
75
<!DOCTYPE html>
<html>
<head>
<title>Random Ron</title>
<link rel="stylesheet" href="assets/css/styles.css">
</head>
<body>
<section>
<h1>Random Ron</h1>
<blockquote id="quote" aria-live="polite">
<em>Getting a fresh quote...</em>
</blockquote>
<p>
<button id="get-quote">More Ron</button>
</p>
</section>
<script src="assets/polyfills/promise.js"></script>
<script src="assets/polyfills/fetch.js"></script>
<script>
// Set up variables
const quote = document.querySelector('#quote');
const btn = document.querySelector('#get-quote');
// Create an array to hold used quotes
var quotes = [];
// Quote function
var getQuote = function () {
fetch('https://ron-swanson-quotes.herokuapp.com/v2/quotes').then(function (response) {
// The API call was successful!
if (response.ok) {
return response.json();
} else {
return Promise.reject(response);
}
}).then(function (data) {
// If the quote is in the quotes array, it's been used already in the last 50 clicks
// Recursively call getQuote() to fetch another quote instead
// Then return to quit the function
if (quotes.indexOf(data[0]) > -1) {
getQuote();
return;
}
// Print quote
quote.textContent = data[0];
quotes.push(data[0]);
// If there are 50 items in the quotes array, reset it
if (quotes.length > 50) {
quotes = [];
}
}).catch(function (err) {
// There was an error
quote.textContent = 'Something went wrong. No quote for you';
});
};
// Call function
getQuote();
// Call function on click
btn.addEventListener('click', getQuote, false);
</script>
</body>
</html>