Last active
October 25, 2022 12:43
-
-
Save angusgrant/111dd9c360744e2cf84a1a9da2da5307 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="utf-8"> | |
<title>Random Ron</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%; | |
} | |
</style> | |
</head> | |
<body> | |
<h1>Random Ron</h1> | |
<blockquote aria-live="assertive"></blockquote> | |
<p> | |
<button id="get-quote">More Ron</button> | |
</p> | |
<script> | |
const blockquoteElem = document.querySelector('blockquote'); | |
// first lets set a click handler | |
document.addEventListener('click', function (event) { | |
//now catch if they are clicking the More Ron button | |
if (event.target.matches('#get-quote')) { | |
//now run the Ajax fetch to get the quote json | |
fetch('https://ron-swanson-quotes.herokuapp.com/v2/quotes').then(function(response) { | |
// If the response is successful, get the JSON | |
if (response.ok) { | |
return response.json(); | |
} | |
//otherwise, throw an error passing the json object through | |
return response.json().then(function (json) { | |
throw json; | |
}); | |
}).then(function (data) { | |
//if successful append the JSON quote item into the blockquote element | |
blockquoteElem.innerText = data; | |
}).catch(function(error) { | |
//if fail display an error in the console. | |
console.warn(error) | |
}); | |
} | |
}); | |
//trigger click on load. | |
//OK a named function would have been better practice than this but this is the route i went down as i didn't read the requirements properly... | |
document.getElementById("get-quote").click(); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment