HTMLify
script.js
Views: 5 | Author: cody
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 postsContainer = document.getElementById('posts-container'); const loading = document.querySelector('.loader'); const filter = document.getElementById('filter'); let limit = 5; let page = 1; // Fetch posts from API async function getPosts() { const res = await fetch( `https://jsonplaceholder.typicode.com/posts?_limit=${limit}&_page=${page}` ); const data = await res.json(); return data; } // Show posts in DOM 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">${post.title}</h2> <p class="post-body">${post.body}</p> </div> `; postsContainer.appendChild(postEl); }); } // Show loader & fetch more posts function showLoading() { loading.classList.add('show'); setTimeout(() => { loading.classList.remove('show'); setTimeout(() => { page++; showPosts(); }, 300); }, 1000); } // Filter posts by input function filterPosts(e) { 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'; } }); } // Show initial posts showPosts(); window.addEventListener('scroll', () => { const { scrollTop, scrollHeight, clientHeight } = document.documentElement; if (scrollHeight - scrollTop === clientHeight) { showLoading(); } }); filter.addEventListener('input', filterPosts); |