Skip to content

Commit fe7124b

Browse files
committed
Add: fetch latest XKCD comic with error handling
1 parent 90bc528 commit fe7124b

3 files changed

Lines changed: 55 additions & 0 deletions

File tree

fetch/programmer-humour/index.html

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
<!DOCTYPE html>
2+
<html lang="en">
3+
<head>
4+
<meta charset="UTF-8">
5+
<title>Programmer Humour</title>
6+
<link rel="stylesheet" href="style.css">
7+
</head>
8+
<body>
9+
10+
<h1>Latest XKCD Comic</h1>
11+
12+
<div id="comic-container">
13+
<p id="loading">Loading comic...</p>
14+
</div>
15+
16+
<script src="script.js"></script>
17+
</body>
18+
</html>

fetch/programmer-humour/script.js

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
function fetchComic() {
2+
const container = document.getElementById("comic-container");
3+
4+
fetch("https://xkcd.now.sh/?comic=latest")
5+
.then(response => {
6+
if (!response.ok) {
7+
throw new Error("Network response was not ok");
8+
}
9+
return response.json();
10+
})
11+
.then(data => {
12+
console.log(data); // requirement
13+
14+
container.innerHTML = `
15+
<h2>${data.title}</h2>
16+
<img src="${data.img}" alt="${data.alt}" />
17+
<p>${data.alt}</p>
18+
`;
19+
})
20+
.catch(error => {
21+
container.innerHTML = `<p>Error loading comic 😢</p>`;
22+
console.error(error);
23+
});
24+
}
25+
26+
window.addEventListener("load", fetchComic);

fetch/programmer-humour/style.css

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
body {
2+
font-family: Arial, sans-serif;
3+
text-align: center;
4+
background-color: #f4f4f4;
5+
}
6+
7+
img {
8+
max-width: 100%;
9+
height: auto;
10+
margin-top: 20px;
11+
}

0 commit comments

Comments
 (0)