In this small project, we will learn to interact with Third party API.
We will use icanhazdadjoke API ( https://icanhazdadjoke.com/api ) to generate random jokes.
We will use
- XMLHttpRequest (XHR) object
- Fetch API
- Async and Await
HTML
<div class="container">
<div class="joke_container">
<div class="joke"></div>
</div>
<button>JOKE GENERATOR</button>
</div>CSS
html {
box-sizing: border-box;
}
*,
*::before,
*::after {
box-sizing: inherit;
}
body {
padding: 0;
margin: 0;
background-color: #4C2A8F;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}
.container {
width: 500px;
display: flex;
flex-direction: column;
justify-content: center;
align-self: center;
}
.joke_container {
height: 200px;
text-align: center;
background-color: #f5b112;
border: 8px solid #000;
padding: 15px;
border-radius: 15px;
display: flex;
justify-content: center;
align-items: center;
}
.joke {
font-size: 1.6rem;
line-height: 1.1;
letter-spacing: 0.3px;
color: #fff;
}
button {
color: #4C2A8F;
font-weight: 600;
font-size: 1.1rem;
padding: 15px;
border-radius: 15px;
}XMLHttpRequest (XHR) object
const joke = document.querySelector('.joke');
const button = document.querySelector('button');
function fetchJoke() {
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://icanhazdadjoke.com/');
xhr.setRequestHeader("Accept", "application/json");
xhr.onreadystatechange = function () {
if (this.readyState === 4 && this.status === 200) {
joke.innerHTML = JSON.parse(this.response).joke;
}
}
xhr.send();
}
button.addEventListener('click', fetchJoke);
document.addEventListener('DOMContentLoaded', fetchJoke);Fetch API
const joke = document.querySelector('.joke');
const button = document.querySelector('button');
function fetchJoke() {
fetch('https://icanhazdadjoke.com/', {
method: 'GET',
headers: { Accept: "application/json" }
})
.then((response) => {
return (response.json())
})
.then((data) => {
joke.innerHTML = data.joke;
})
}
button.addEventListener('click', fetchJoke);
document.addEventListener('DOMContentLoaded', fetchJoke);Async and Await
const joke = document.querySelector('.joke');
const button = document.querySelector('button');
async function fetchJoke() {
const response = await fetch('https://icanhazdadjoke.com/', {
method: 'GET',
headers: { Accept: "application/json" }
});
const data = await response.json();
joke.innerHTML = data.joke
}
button.addEventListener('click', fetchJoke);
document.addEventListener('DOMContentLoaded', fetchJoke);Let’s rewrite Async and Await with arrow function.
const fetchJoke = async () => {
const response = await fetch('https://icanhazdadjoke.com/', {
method: 'GET',
headers: { Accept: "application/json" }
});
const data = await response.json();
joke.innerHTML = data.joke
}
