Skip to content

Instantly share code, notes, and snippets.

@angusgrant
Created October 29, 2022 12:41
Show Gist options
  • Save angusgrant/b9ed144a0106ab714838cb7696a4b210 to your computer and use it in GitHub Desktop.
Save angusgrant/b9ed144a0106ab714838cb7696a4b210 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Random Ron - No Duplicates</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style type="text/css">
body {
margin: 0 auto;
max-width: 40em;
width: 88%;
}
img {
height: auto;
max-width: 100%;
width: 100%;
}
</style>
</head>
<body>
<h1>Random Ron - No Duplicates</h1>
<img alt="Ron Swanson standing in front of a buffet stating, 'I've said too much.'" src="https://giphygifs.s3.amazonaws.com/media/iofbYa67AbBg4/giphy.gif">
<blockquote id="quote" aria-live="polite">
<em>Getting a fresh quote...</em>
</blockquote>
<p>
<button id="get-quote">More Ron</button>
</p>
<script>
// Get the blockquote and button elements
let quote = document.querySelector('#quote');
let btn = document.querySelector('#get-quote');
let quoteArrayList = [];
// Get a fresh quote and render it into the DOM
async function getQuote () {
try {
const response = await fetch('https://ron-swanson-quotes.herokuapp.com/v2/quotes');
if (!response.ok){
throw '[Something went wrong, sorry!] I have a joke for you... The government in this town is excellent, and uses your tax dollars efficiently.';
}
const data = await response.json();
if (checkPrevQuoteExists(data[0])){
quote.textContent = data[0];
}
} catch (error) {
console.warn(error);
}
}
function checkPrevQuoteExists(quote) {
if (quoteArrayList.includes(quote)) {
//if Quote is already in the array then call getQuote() again.
getQuote();
// and dont display duplicate quote
return false;
} else if (quoteArrayList.length === 50){
quoteArrayList.shift();
quoteArrayList.push(quote);
return true;
} else {
quoteArrayList.push(quote);
return true;
}
}
// Get a quote on page load
getQuote();
// Get a quote when the #get-quote button is clicked
btn.addEventListener('click', getQuote);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment