Skip to content

ITP-25 LON | MIKIYAS GEBREMICHAEL | MODULE-DATA-FLOWS | Programmer Humour- Mini API project | SPRINT-3 / WEEK-3 #175

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 6 commits into from
Closed
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
15 changes: 15 additions & 0 deletions fetch/programmer-humour/xkcd.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
/*styling for the body, container and image*/
body {
font-family: Arial, sans-serif;
text-align: center;
margin: 20px;
}
#comic-container {
display: flex;
flex-direction: column;
align-items: center;
}
img {
max-width: 100%;
height: auto;
}
16 changes: 16 additions & 0 deletions fetch/programmer-humour/xkcd.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>XKCD Comic Viewer</title>
<link rel="stylesheet" href="xkcd.css">
<script src="xkcd.js" defer ></script>
</head>
<body>
<h1>Latest XKCD Comic</h1>
<div id="comic-container">
<p>Loading...</p>
</div>
</body>
</html>
32 changes: 32 additions & 0 deletions fetch/programmer-humour/xkcd.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
document.addEventListener('DOMContentLoaded', () =>{
fetchComic();
});
const fetchComic = async ()=>{
try {
const response = await fetch('https://xkcd.now.sh/?comic=latest'); //try fetching data from the link
if (!response.ok) { //and if this is false throw a new error for the status of our response.
throw new Error(`HTTP error! Status: ${response.status}`);
}
const data = await response.json(); //wait for the response and if we get it parse in to our json file.

const comicContainer = document.getElementById('comic-container'); //get comic container from html.
comicContainer.innerHTML = '';

const title = document.createElement('h2');
title.textContent = data.title;
comicContainer.appendChild(title);

const img = document.createElement('img');
img.src = data.img;
img.alt = data.alt;
comicContainer.appendChild(img);

const altText = document.createElement('p');
altText.textContent = data.alt;
comicContainer.appendChild(altText);
} catch (error) { //if their is any error cache it and console log the error
console.error('Failed to load comic ... Error fetching comic:', error);
comicContainer.textContent = 'Failed to load comic. Please try again later.';
}

};