Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions fetch/programmer-humour/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Programmer humour</title>
<link rel="stylesheet" href="style.css">
<script src="script.js" defer></script>
</head>

<body>
<h1>Programmer humour</h1>
<img src="" alt="">

</body>

</html>
35 changes: 35 additions & 0 deletions fetch/programmer-humour/script.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
const endpointAPI = "https://xkcd.now.sh/?comic=latest";

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

endpointAPI is used both outside and inside the function. This can be confusing, so Its best to rename the function parameter to make the code clearer and avoid shadowing.

more on shadowing here:
https://www.geeksforgeeks.org/javascript/variable-shadowing-in-javascript/

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is now corrected. thank you

async function fetchData(url) {
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Error! Status: ${response.status}`);
}

const data = await response.json();

console.log(data);
return data;
} catch (error) {
console.error("Could not fetch data", error);
}
}

async function loadComic() {
try {
const data = await fetchData(endpointAPI);
if (!data) {
throw new Error("No data received from the API.");
}
const imgEl = document.querySelector("img");
imgEl.src = data.img;
imgEl.title = data.title;
imgEl.alt = data.alt;
} catch (error) {
console.error("Error loading comic:", error);
document.querySelector("h1").textContent =
"Image failed loading. Please try again later";
}
}

loadComic();
15 changes: 15 additions & 0 deletions fetch/programmer-humour/style.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
body {
background-color: #e0f5f5;
font-family: sans-serif;
text-align: center;
padding: 2rem;
}

h1 {
color: #1a6b6b;
font-size: 3rem;
}

/* img {
margin: 0 auto;
} */
Loading