Hello Coders! Welcome to JS Project Blog. In this, Let's create a fun project and learn something new out of it. We all love jokes right?๐. Especially if it's related to our genre. Like coding. There's an API which provides you Programming Jokes in JSON format. Let's use that and create a Random Joke Generator.
Here's a preview-
That being said, let us get started.
Step - 1: Like always, create 3 files - index.html, style.css and script.js
Step - 2: Copy the below HTML code and paste it into your code editor.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Random Joke Generator</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="wrapper">
<span>Random Joke Generator</span>
<p id="joke"></p>
<button id="btn">Generate Joke</button>
</div>
<script src="script.js"></script>
</body>
</html>
Step - 3: Below is the CSS code for styling.
CSS
@import url('https://fonts.googleapis.com/css2?family=Poppins&display=swap');
* {
padding: 0;
margin: 0;
box-sizing: border-box;
font-family: "Rubik", sans-serif;
}
body {
background: #f6f7fc;
}
.wrapper {
width: 400px;
padding: 50px 40px;
background: linear-gradient(45deg,rgba(183, 64, 150, 1) 0%,rgba(255, 0, 69, 1) 100%);
position: absolute;
transform: translate(-50%, -50%);
top: 50%;
left: 50%;
border-radius: 15px;
box-shadow: 2px 31px 35px -15px rgba(0,0,0,0.64);
}
span {
display: block;
text-align: center;
margin-top: -30px;
color: #f6f7fc;
font-size: 25px;
font-family: "Poppins", sans-serif;
font-weight: 800;
}
p {
background: #f6f7fc;
font-size: 14px;
border-radius: 15px;
font-weight: 400;
text-align: center;
word-wrap: break-word;
line-height: 30px;
margin: 50px 0;
opacity: 0;
font-family: "Poppins", sans-serif;
box-shadow: 3px 16px 41px -8px rgba(255, 255, 255, 0.37);
}
.fade {
opacity: 1;
transition: opacity 0.1s;
}
button {
display: block;
background-color: transparent;
border: 2px solid;
padding: 5px;
font-size: 18px;
color: #e7e7ec;
font-weight: 800;
padding: 12px 25px;
margin: 0 auto;
border-radius: 50px;
cursor: pointer;
outline: none;
}
Step - 4: Below is the JavaScript code for adding and removing the class.
JS
const jokeContainer = document.getElementById("joke");
const btn = document.getElementById("btn");
const url =
"https://v2.jokeapi.dev/joke/Any?blacklistFlags=nsfw,religious,political,racist,sexist,explicit&type=single";
let getJoke = () => {
jokeContainer.classList.remove("fade");
fetch(url)
.then((data) => data.json())
.then((item) => {
jokeContainer.textContent = `${item.joke}`;
jokeContainer.classList.add("fade");
});
};
btn.addEventListener("click", getJoke);
getJoke();
And that's it. You're done.
Let me know in the comments if you have any doubt related to this.
Follow @creocodigo for more projects and web related content.
If you find this useful, below are some other posts that I am sure you'll love