diff --git a/fetch/programmer-humour/index.html b/fetch/programmer-humour/index.html new file mode 100644 index 00000000..3743444d --- /dev/null +++ b/fetch/programmer-humour/index.html @@ -0,0 +1,21 @@ + + + + + + Programmer Humour + + + +
+

Programmer Humour

+

Latest XKCD comic fetched from an API.

+ +
+

Loading comic...

+
+
+ + + + diff --git a/fetch/programmer-humour/script.js b/fetch/programmer-humour/script.js new file mode 100644 index 00000000..8d09d765 --- /dev/null +++ b/fetch/programmer-humour/script.js @@ -0,0 +1,48 @@ +const comicContainer = document.getElementById("comic-container"); + +async function fetchLatestComic() { + comicContainer.innerHTML = "

Loading comic...

"; + + try { + const response = await fetch("https://xkcd.now.sh/?comic=latest"); + + if (!response.ok) { + throw new Error(`HTTP error! Status: ${response.status}`); + } + + const comicData = await response.json(); + console.log(comicData); + + renderComic(comicData); + } catch (error) { + console.error("Failed to fetch comic:", error); + showError("Sorry, the comic could not be loaded. Please try again later."); + } +} + +function renderComic(comicData) { + comicContainer.innerHTML = ""; + + const title = document.createElement("h2"); + title.className = "comic-title"; + title.textContent = comicData.safe_title || "Latest XKCD Comic"; + + const image = document.createElement("img"); + image.src = comicData.img; + image.alt = comicData.alt || comicData.safe_title || "XKCD comic"; + + comicContainer.appendChild(title); + comicContainer.appendChild(image); +} + +function showError(message) { + comicContainer.innerHTML = ""; + + const errorText = document.createElement("p"); + errorText.className = "error-message"; + errorText.textContent = message; + + comicContainer.appendChild(errorText); +} + +fetchLatestComic(); diff --git a/fetch/programmer-humour/style.css b/fetch/programmer-humour/style.css new file mode 100644 index 00000000..c0ea1a17 --- /dev/null +++ b/fetch/programmer-humour/style.css @@ -0,0 +1,36 @@ +body { + margin: 0; + font-family: Arial, sans-serif; + background-color: #f4f4f4; + color: #222; +} + +.container { + max-width: 900px; + margin: 0 auto; + padding: 2rem 1rem; + text-align: center; +} + +.comic-container { + margin-top: 2rem; + padding: 1.5rem; + background-color: white; + border: 1px solid #ddd; + border-radius: 8px; +} + +.comic-container img { + max-width: 100%; + height: auto; + border-radius: 6px; +} + +.comic-title { + margin-bottom: 1rem; +} + +.error-message { + color: #b00020; + font-weight: bold; +}