Skip to content
Merged
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
40 changes: 40 additions & 0 deletions index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}

body {
padding: 1rem;
display: grid;
place-items: center;
}

.post {
margin: 1rem;
padding: 1rem;
border: 0.125rem solid black;
}

h1 {
padding: 1rem;
}
</style>
<body>
<button id="fetch-api-button">Click To Fetch</button>
<h1>API Titles</h1>
<div class="append-titles">
</div>


<script src="./script.js"></script>
</body>
</html>
39 changes: 39 additions & 0 deletions script.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@

const postApi = "https://jsonplaceholder.typicode.com/todos";

// Fetch API Function
async function fetchTodo(apiUrl) {
try {
const response = await fetch(apiUrl);
if (!response.ok) {
throw new Error('Network response was not ok');
}
const json = await response.json();
return json;
} catch (error) {
console.error('There was a problem with the fetch operation:', error);
}
}


// Append data in DOM
function appendData(data) {
const container = document.querySelector('.append-titles');
data.forEach((item) => {
const newTitle = document.createElement('div');
newTitle.className = 'post';
newTitle.innerHTML = item.title;
container.appendChild(newTitle);
});
}

// Helper function to store data from fetch function and pass on to appendData function
async function clickHandler() {
const data = await fetchTodo(postApi);
appendData(data);
}

window.onload = () => {
const button = document.getElementById('fetch-api-button');
button.addEventListener('click', clickHandler);
}