Random Joke App with API in JavaScript | Source Code

0

 

Uploading: 186524 of 186524 bytes uploaded.


Today we have brought you a Random Joke App using API in JavaScript with Source Code. 

HTML Code 

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Image Slider by JavaScript | Chamod Dilshan </title>
<link rel="stylesheet" href="styles.css">
</head>
<body>

<div class="wrapper">
<span>😂</span>
<p id="joke">

</p>
<button id="Btn">Get Random Joke</button>
</div>

<script src="script.js"></script>

</body>
</html>
CSS Code
*{
padding: 0;
margin: 0;
box-sizing: border-box;
font-family: Verdana, Geneva, Tahoma, sans-serif;
}

body{
background-color: rgb(61,101,231);
}
.wrapper{
width: 80vmin;
padding: 50px 40px;
background-color: rgb(33, 32, 32);
position: absolute;
transform: translate(-50% , -50%);
top: 50%;
left: 50%;
border-radius: 10px;
box-shadow: 20px 20px 40px rgba(82, 82, 82, 0.288);

}

span{
display: block;
width: 100%;
text-align: center;
font-size:100px ;
}

p{
font-size: 20px;
color: white;
font-weight: 600;
text-align: center;
word-wrap: break-word;
line-height: 35px;
margin: 30px 0;
}

button{
display: block;
background-color: rgb(61,101,231);
border: none;
border-radius: 10px;
padding: 12px 15px;
font-size: 18px;
color: white;
font-weight: bold;
margin: 0 auto;
cursor: pointer;
}
JavaScript Code
const jokeContainer = document.getElementById("joke");
const Btn = document.getElementById("Btn");
const url = "https://v2.jokeapi.dev/joke/Any?type=single";

let getJoke = () =>{
fetch(url)
.then(data =>data.json())
.then(item => {
jokeContainer.textContent = `${item.joke}`;

});
}

Btn.addEventListener("click",()=>{
getJoke();
});

 Explanation of the Logic 

Selecting Elements:

The code starts by selecting two elements from the HTML:

jokeContainer is the paragraph element where the joke will be displayed.

Btn is the button that will trigger fetching a new joke.

API URL:

The url variable holds the endpoint of the JokeAPI that provides a random joke.

Fetch Joke Function:

The getJoke function is defined to fetch a joke from the API:

It uses the fetch method to send a request to the API.

When the data is received, it is converted to JSON format.

The joke from the JSON response is then placed inside the jokeContainer paragraph.

API SITE — Link

Button Click Event:

An event listener is added to the button:

When the button is clicked, the getJoke function is called, fetching and displaying a new joke.

This JavaScript code ensures that every time the button is clicked, a new random joke is fetched from the API and displayed on the web page.


How to run this ?

Create an folder in your computer called Random Joke App. Then Create index.html , styles.css and script.js files. Then copy the above codes in the relevant files. Then open the index.html in your web browser. 



Post a Comment

0Comments
Post a Comment (0)