-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
48 lines (44 loc) · 1.51 KB
/
script.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
// grab a reference for necessary HTML elements
// .joke-text
const jokeText = document.querySelector(".joke-text");
// .new-joke-btn
const newJokeBtn = document.querySelector(".new-joke-btn");
// .tweet-btn (link)
const tweetBtn = document.querySelector(".tweet-btn");
// add 'click' eventListener to .new-joke-btn
newJokeBtn.addEventListener("click", getJoke);
// immediately call getJoke()
getJoke();
// getJoke() function definition
function getJoke() {
// make an API request to https://icanhazdadjoke.com/'
fetch("https://icanhazdadjoke.com/", {
headers: {
Accept: "application/json"
}
})
.then(function (response) {
/* convert Stringified JSON response to Javascript Object */
return response.json();
})
.then(function (data) {
/* replace innerText of .joke-text with data.joke */
// extract the joke text
const joke = data.joke;
// do the replacement
jokeText.innerText = joke;
/* make the tweetBtn(.tweet-btn link) work by setting href */
// create tweet link with joke
const tweetLink = `https://twitter.com/share?text=${joke}`;
// set the href
tweetBtn.setAttribute("href", tweetLink);
})
.catch(function (error) {
// if some error occured
jokeText.innerText = "Oops! Some error happened :(";
// removes the old href from .tweet-btn if found any
tweetBtn.removeAttribute("href");
// console log the error
console.log(error);
});
}