Saturday, September 26, 2020

Javascript Random joke generator using API

ALERT: This post requires basic knowledge of HTML, CSS, and Javascript and you are good to go if you know this!






 HTML Part 

<div class="container">

<h1>Random joke generator using api></h1>

<div class="joke_area"> Joke will appear here!</div>

<button onclick= "new_joke">New joke</button>

<button onclick="tweet"> Tweet</button>

</div>

CSS Part

It will depend on your creativity. So I leave that part on you


Js Part

So before coding the javascript part, we must brainstorm the logic on paper we are going to apply. So this will involve a simple algorithm for this project. 

first, we will select all the HTML elements using the query selector method, then we will add an event listener to the buttons, and create functions to get new jokes and tweet that joke.

The newjoke() function will fetch the API, collect the response, convert the response into JSON type.


As the JSON data has many different values but we want the only a joke so we will select the joke and replace that with the joke area.  


//selecting the joke_area and buttons 

const jokearea = document.querySelector('.joke_area');

const jokebutton= socument.querySelector('.new_joke')

// we created 2 constants and in brackets we have to put the class name we want to select.

then we will create a new function, that will call or fetch the API, accept the response, convert the response into json format, extract the desired joke data, replace the joke in the joke_area.

function new_joke(){

fetch(''https://icanhazdadjoke.com/'' , 

{ headers: {'Accept': 'application/json' }})

.then(function(response)

{ return response.json(); })

.then(function(data)

cont joke=data.joke;

joke_area.innerText= joke;

)}


function tweet(){



}














 )












}


















0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home