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