diff --git a/fetch/programmer-humour/assets/no_image.webp b/fetch/programmer-humour/assets/no_image.webp new file mode 100644 index 000000000..04a412ac1 Binary files /dev/null and b/fetch/programmer-humour/assets/no_image.webp differ diff --git a/fetch/programmer-humour/index.html b/fetch/programmer-humour/index.html new file mode 100644 index 000000000..3eb05b153 --- /dev/null +++ b/fetch/programmer-humour/index.html @@ -0,0 +1,14 @@ + + + + + + Programmer Humour + + + + +

Programmer Humour

+
+ + diff --git a/fetch/programmer-humour/script.js b/fetch/programmer-humour/script.js new file mode 100644 index 000000000..77023db5a --- /dev/null +++ b/fetch/programmer-humour/script.js @@ -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(); diff --git a/fetch/programmer-humour/style.css b/fetch/programmer-humour/style.css new file mode 100644 index 000000000..cf6fc0f18 --- /dev/null +++ b/fetch/programmer-humour/style.css @@ -0,0 +1,4 @@ +img { + margin: 0 auto; + width: 500px; +}