Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file added fetch/programmer-humour/assets/no_image.webp
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
14 changes: 14 additions & 0 deletions fetch/programmer-humour/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Programmer Humour</title>
<link href="style.css" rel="stylesheet" />
<script src="script.js" defer></script>
</head>
<body>
<h1>Programmer Humour</h1>
<main id="comic-container"></main>
</body>
</html>
51 changes: 51 additions & 0 deletions fetch/programmer-humour/script.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
const fallbackImg = "./assets/no_image.webp";
const endpointAPI = "https://xkcd.now.sh/?comic=latest";

const container = document.getElementById("comic-container");

const imgEl = document.createElement("img");
imgEl.src = fallbackImg;
imgEl.alt = "Loading comic...";

imgEl.onerror = () => {
imgEl.src = fallbackImg;
imgEl.alt = "Failed to load comic";
};

if (container) {
container.appendChild(imgEl);
}

const fetchData = async () => {
try {
const response = await fetch(endpointAPI);
if (!response.ok) {
throw new Error(`Network response status: ${response.status}`);
}
const data = await response.json();
return data;
} catch (error) {
console.log("Error fetching data:", error);
return null;
}
};

const renderComic = async () => {
if (!container) {
console.error("Comic container not found in DOM");
return;
}

const data = await fetchData();
console.log(data);
if (data && data.img) {
imgEl.src = data.img;
imgEl.alt = data.alt || data.title || "Programmer humour comic";
} else {
console.error("Image data not received");
imgEl.src = fallbackImg;
imgEl.alt = "No image available";
}
};

renderComic();
4 changes: 4 additions & 0 deletions fetch/programmer-humour/style.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
img {
margin: 0 auto;
width: 500px;
}
Loading