forked from solygambas/html-css-javascript-projects
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
73 lines (64 loc) · 1.92 KB
/
script.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
const postsContainer = document.getElementById("posts-container");
const loading = document.getElementById("loader");
const filter = document.getElementById("filter");
let limit = 5;
let page = 1;
let isLoading = false;
async function getPosts() {
const res = await fetch(
`https://jsonplaceholder.typicode.com/posts?_limit=${limit}&_page=${page}`
);
const data = await res.json();
return data;
}
function capitalize(text) {
return text.charAt(0).toUpperCase() + text.slice(1);
}
async function showPosts() {
const posts = await getPosts();
posts.forEach((post) => {
const postEl = document.createElement("div");
postEl.classList.add("post");
postEl.innerHTML = `
<div class="number">${post.id}</div>
<div class="post-info">
<h2 class="post-title">${capitalize(post.title)}</h2>
<p class="post-body">${capitalize(post.body)}</p>
</div>
`;
postsContainer.appendChild(postEl);
});
}
function showLoading() {
isLoading = true;
loader.classList.add("show");
setTimeout(() => {
loader.classList.remove("show");
setTimeout(() => {
page++;
showPosts();
}, 300);
isLoading = false;
}, 1000);
}
function filterPosts(e) {
console.log("running");
const term = e.target.value.toUpperCase();
const posts = document.querySelectorAll(".post");
posts.forEach((post) => {
const title = post.querySelector(".post-title").innerText.toUpperCase();
const body = post.querySelector(".post-body").innerText.toUpperCase();
if (title.indexOf(term) > -1 || body.indexOf(term) > -1) {
post.style.display = "flex";
} else {
post.style.display = "none";
}
});
}
window.addEventListener("scroll", () => {
const { scrollTop, scrollHeight, clientHeight } = document.documentElement;
if (scrollTop + clientHeight >= scrollHeight - 5 && !isLoading) showLoading();
});
filter.addEventListener("input", filterPosts);
// Init
showPosts();