new class js -advanced
This commit is contained in:
@@ -0,0 +1,73 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Display Post Details</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1>List of Posts</h1>
|
||||
<ul id="post-list"></ul>
|
||||
|
||||
<div
|
||||
id="post-details"
|
||||
style="
|
||||
display: none;
|
||||
border: 1px solid #ccc;
|
||||
padding: 1em;
|
||||
margin-top: 1em;
|
||||
"
|
||||
>
|
||||
<h2 id="post-title"></h2>
|
||||
<p id="post-body"></p>
|
||||
<button id="close-details">Close Details</button>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
'use strict';
|
||||
|
||||
async function loadAndDisplayPosts() {
|
||||
const postList = document.getElementById('post-list');
|
||||
const postDetails = document.getElementById('post-details');
|
||||
const postTitle = document.getElementById('post-title');
|
||||
const postBody = document.getElementById('post-body');
|
||||
const closeDetailsButton = document.getElementById('close-details');
|
||||
|
||||
try {
|
||||
const response = await fetch('https://dummyjson.com/posts');
|
||||
if (!response.ok) {
|
||||
throw new Error('Network response was not ok');
|
||||
}
|
||||
const posts = await response.json();
|
||||
|
||||
posts.forEach((post) => {
|
||||
const listItem = document.createElement('li');
|
||||
listItem.textContent = post.title;
|
||||
listItem.style.cursor = 'pointer';
|
||||
|
||||
// Add click event listener to display post details
|
||||
listItem.addEventListener('click', () => {
|
||||
postTitle.textContent = post.title;
|
||||
postBody.textContent = post.body;
|
||||
postDetails.style.display = 'block';
|
||||
});
|
||||
|
||||
postList.appendChild(listItem);
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error fetching posts:', error);
|
||||
const errorItem = document.createElement('li');
|
||||
errorItem.textContent = 'Error loading posts.';
|
||||
postList.appendChild(errorItem);
|
||||
}
|
||||
|
||||
// Close details when the button is clicked
|
||||
closeDetailsButton.addEventListener('click', () => {
|
||||
postDetails.style.display = 'none';
|
||||
});
|
||||
}
|
||||
|
||||
loadAndDisplayPosts();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
Reference in New Issue
Block a user