Skip to content

Commit 5a88cd1

Browse files
committed
Implement random XKCD comic fetching with button for new comic
1 parent ce3d13d commit 5a88cd1

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

fetch/programmer-humour/script.js

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
let latestNum = null; // Store latest comic number
2+
3+
async function fetchRandomComic() {
4+
const container = document.getElementById('comic-container');
5+
6+
try {
7+
// Get latest comic number if not already fetched
8+
if (!latestNum) {
9+
const latestResponse = await fetch('https://xkcd.now.sh/?comic=latest');
10+
if (!latestResponse.ok) {
11+
throw new Error(`HTTP error getting latest: ${latestResponse.status}`);
12+
}
13+
const latestData = await latestResponse.json();
14+
latestNum = latestData.num;
15+
}
16+
17+
// Pick a random comic number between 1 and latestNum
18+
const randomNum = Math.floor(Math.random() * latestNum) + 1;
19+
20+
// Fetch the random comic
21+
const response = await fetch(`https://xkcd.now.sh/?comic=${randomNum}`);
22+
if (!response.ok) {
23+
throw new Error(`HTTP error getting comic: ${response.status}`);
24+
}
25+
26+
const data = await response.json();
27+
console.log('Fetched comic data:', data);
28+
29+
// Clear container
30+
container.innerHTML = '';
31+
32+
// Add title
33+
const title = document.createElement('div');
34+
title.className = 'comic-title';
35+
title.textContent = `#${data.num}${data.title}`;
36+
container.appendChild(title);
37+
38+
// Add comic image
39+
const img = document.createElement('img');
40+
img.src = data.img;
41+
img.alt = data.alt;
42+
img.title = data.alt;
43+
container.appendChild(img);
44+
45+
} catch (error) {
46+
console.error('Error fetching the comic:', error);
47+
container.innerHTML = `<p style="color:red;">Failed to load comic. Try again later.</p>`;
48+
}
49+
}
50+
51+
// Load first comic when page starts
52+
fetchRandomComic();
53+
54+
// Add button click handler
55+
document.getElementById('new-comic-btn').addEventListener('click', fetchRandomComic);

0 commit comments

Comments
 (0)