-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
80 lines (62 loc) · 1.96 KB
/
main.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
74
75
76
77
78
79
80
const postContainer = document.querySelector('#post-container');
const loading = document.querySelector('.loader');
const filter = document.querySelector('#filter');
let limit = 4;
let page = 1;
//Function to get the posts from json placeholder
async function getPosts() {
const res = await fetch(`https://jsonplaceholder.typicode.com/posts?_limit=${limit}&_page=${page}`);
const data = await res.json();
return data;
}
//Filter posts on search
function filterPosts(e) {
const search = 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(search) > -1 || body.indexOf(search) > -1) {
post.style.display = 'flex';
} else{
post.style.display = 'none';
}
});
}
//function to show post on DOM
async function showPosts() {
const posts = await getPosts();
posts.forEach(post => {
const postEl = document.createElement('div');
postEl.classList.add('post');
postEl.innerHTML = `
<div class="post-info">
<h2 class="post-title">${post.title}</h2>
<p class="post-body">
${post.body}
</p>
</div>
`;
postContainer.appendChild(postEl);
});
}
//Show loading and fetch more posts
function showLoading() {
loading.classList.add('show');
setTimeout(() => {
loading.classList.remove('show');
setTimeout(() => {
page++;
showPosts();
}, 200);
}, 1000);
}
//Show posts initially
showPosts();
window.addEventListener('scroll', () => {
const { scrollTop, scrollHeight, clientHeight } = document.documentElement;
if (scrollTop + clientHeight >= scrollHeight - 5){
showLoading();
}
});
filter.addEventListener('input', filterPosts);