diff --git a/fetch/programmer-humour/index.html b/fetch/programmer-humour/index.html new file mode 100644 index 00000000..5102ad86 --- /dev/null +++ b/fetch/programmer-humour/index.html @@ -0,0 +1,20 @@ + + + + + + Programmer Humour - XKCD Comics + + + +

😂 Programmer Humour

+ +
+

Loading comic...

+
+ + + + + + \ No newline at end of file diff --git a/fetch/programmer-humour/script.js b/fetch/programmer-humour/script.js new file mode 100644 index 00000000..ef7b8f80 --- /dev/null +++ b/fetch/programmer-humour/script.js @@ -0,0 +1,53 @@ +// Reusable function for fetching JSON with error handling +async function fetchJson(url) { + const response = await fetch(url); + if (!response.ok) { + throw new Error(`HTTP error! status: ${response.status}`); + } + return await response.json(); +} + +let latestNum = null; // cache latest comic number + +async function fetchRandomComic() { + const container = document.getElementById('comic-container'); + + try { + // Get latest comic number if not cached + if (!latestNum) { + const latestData = await fetchJson('https://xkcd.now.sh/?comic=latest'); + latestNum = latestData.num; + } + + // Pick a random comic number + const randomNum = Math.floor(Math.random() * latestNum) + 1; + + // Fetch the random comic + const data = await fetchJson(`https://xkcd.now.sh/?comic=${randomNum}`); + + // Render comic + container.innerHTML = ''; + + const title = document.createElement('div'); + title.className = 'comic-title'; + title.textContent = `#${data.num} – ${data.title}`; + container.appendChild(title); + + const img = document.createElement('img'); + img.src = data.img; + img.alt = data.alt; + img.title = data.alt; + container.appendChild(img); + + } catch (error) { + console.error('Error fetching comic:', error); + container.innerHTML = `

Failed to load comic. Try again later.

`; + } +} + +// Load first comic on page load +fetchRandomComic(); + +// Add button click handler +document.getElementById('new-comic-btn') + .addEventListener('click', fetchRandomComic); \ No newline at end of file diff --git a/fetch/programmer-humour/style.css b/fetch/programmer-humour/style.css new file mode 100644 index 00000000..3736e082 --- /dev/null +++ b/fetch/programmer-humour/style.css @@ -0,0 +1,43 @@ +body { + font-family: Arial, sans-serif; + text-align: center; + background-color: #f4f4f4; + margin: 0; + padding: 20px; +} + +h1 { + color: #333; +} + +#comic-container { + margin-top: 20px; +} + +.comic-title { + font-weight: bold; + font-size: 1.2rem; + margin-bottom: 10px; +} + +#comic-container img { + max-width: 100%; + height: auto; + border: 2px solid #ccc; + border-radius: 8px; +} + +button { + margin-top: 20px; + padding: 10px 15px; + font-size: 1rem; + background-color: #0078d4; + color: white; + border: none; + border-radius: 6px; + cursor: pointer; +} + +button:hover { + background-color: #005a9e; +} \ No newline at end of file