Skip to content

Commit 7449eb5

Browse files
committed
Fetch Image using fetch API
1 parent 050beed commit 7449eb5

3 files changed

Lines changed: 71 additions & 0 deletions

File tree

fetch/programmer-humour/index.html

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
<!DOCTYPE html>
2+
<html lang="en">
3+
<head>
4+
<meta charset="UTF-8">
5+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
6+
<title>Programmer humour</title>
7+
<link rel="stylesheet" href="style.css">
8+
<script src="script.js" defer></script>
9+
</head>
10+
<body>
11+
<header>
12+
<h1>Who knew programmers could be funny?</h1>
13+
</header>
14+
<div id="container" class="content">
15+
16+
</div>
17+
</body>
18+
</html>

fetch/programmer-humour/script.js

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
const container = document.getElementById('container');
2+
const img = document.createElement('img');
3+
4+
container.appendChild(img);
5+
img.style.width = '100%';
6+
img.style.height = 'auto';
7+
8+
function fetchImage() {
9+
fetch('https://xkcd.vercel.app/?comic=latest') // or the ridvanaltun endpoint
10+
.then(r => {
11+
if (!r.ok) throw new Error(`HTTP ${r.status} ${r.statusText}`);
12+
return r.json();
13+
})
14+
.then(data => {
15+
console.log('XKCD data:', data); // logs the JSON
16+
img.src = data.img || data.imageUrl || data.image;
17+
img.alt = data.alt || data.title || 'XKCD comic';
18+
})
19+
.catch(err => {
20+
console.error('Error fetching image:', err);
21+
container.textContent = 'Could not load the comic.';
22+
});
23+
}
24+
25+
fetchImage();

fetch/programmer-humour/style.css

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
body {
2+
font-family: sans-serif;
3+
margin: 0;
4+
padding: 1rem;
5+
background: #fafafa;
6+
color: #333;
7+
}
8+
9+
header {
10+
text-align: center;
11+
margin-bottom: 1.5rem;
12+
}
13+
14+
.content {
15+
max-width: 800px;
16+
margin: 0 auto;
17+
}
18+
19+
img {
20+
display: block;
21+
max-width: 100%;
22+
height: auto;
23+
border: 1px solid #ddd;
24+
background: white;
25+
padding: 0.5rem;
26+
box-shadow: 0 2px 6px rgba(0,0,0,0.08);
27+
}
28+

0 commit comments

Comments
 (0)