-
Notifications
You must be signed in to change notification settings - Fork 0
/
generator.js
33 lines (28 loc) · 1.07 KB
/
generator.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
const jokeContainer = document.getElementById("joke");
const categoryButtons = document.querySelectorAll(".category-btn");
const apiUrl = "https://v2.jokeapi.dev/joke";
function fetchJoke(category) {
const url = category ? `${apiUrl}/${category}` : apiUrl;
fetch(url)
.then((response) => response.json())
.then((data) => {
if (data.type === "single") {
jokeContainer.textContent = data.joke;
} else if (data.type === "twopart") {
jokeContainer.textContent = `${data.setup}\n${data.delivery}`;
}
})
.catch((error) => {
jokeContainer.textContent = "Failed to fetch joke. Please try again later.";
console.error(error);
});
}
function handleCategoryButtonClick(event) {
const category = event.target.getAttribute("data-category");
fetchJoke(category);
}
categoryButtons.forEach((button) => {
button.addEventListener("click", handleCategoryButtonClick);
});
// Fetch a random joke on page load
fetchJoke();