1+ // grab a reference for necessary HTML elements
2+ // .joke-text
3+ const jokeText = document . querySelector ( '.joke-text' ) ;
4+ // .new-joke-btn
5+ const newJokeBtn = document . querySelector ( '.new-joke-btn' ) ;
6+ // .tweet-btn (link)
7+ const tweetBtn = document . querySelector ( '.tweet-btn' ) ;
8+
9+ // add 'click' eventListener to .new-joke-btn
10+ newJokeBtn . addEventListener ( 'click' , getJoke ) ;
11+
12+ // immediately call getJoke()
13+ getJoke ( ) ;
14+
15+ // getJoke() function definition
16+ function getJoke ( ) {
17+ // make an API request to https://icanhazdadjoke.com/'
18+ fetch ( 'https://icanhazdadjoke.com/' , {
19+ headers : {
20+ 'Accept' : 'application/json'
21+ }
22+ } ) . then ( function ( response ) {
23+ /* convert Stringified JSON response to Javascript Object */
24+ return response . json ( ) ;
25+ } ) . then ( function ( data ) {
26+ /* replace innerText of .joke-text with data.joke */
27+ // extract the joke text
28+ const joke = data . joke ;
29+ // do the replacement
30+ jokeText . innerText = joke ;
31+
32+ /* make the tweetBtn(.tweet-btn link) work by setting href */
33+ // create tweet link with joke
34+ const tweetLink = `https://twitter.com/share?text=${ joke } ` ;
35+ // set the href
36+ tweetBtn . setAttribute ( 'href' , tweetLink ) ;
37+ } ) . catch ( function ( error ) {
38+ // if some error occured
39+ jokeText . innerText = 'Oops! Some error happened :(' ;
40+ // removes the old href from .tweet-btn if found any
41+ tweetBtn . removeAttribute ( 'href' ) ;
42+ // console log the error
43+ console . log ( error ) ;
44+ } ) ;
45+ }
0 commit comments