Infinite scroll은 Paging 하는것을 대신해서 스크롤을 내릴때 리스트를 불러오는 기능을 말한다.
아래처럼 단순하게도 구현이 가능하다.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript Infinite Scroll</title>
</head>
<body>
<ul id='infinite-list'>
</ul>
<script>
var listElm = document.querySelector('#infinite-list');
// Add 20 items.
var nextItem = 1;
var loadMore = function() {
for (var i = 0; i < 20; i++) {
var item = document.createElement('li');
item.innerText = 'Item ' + nextItem++;
listElm.appendChild(item);
}
}
// Detect when scrolled to bottom.
listElm.addEventListener('scroll', function() {
if (listElm.scrollTop + listElm.clientHeight >= listElm.scrollHeight) {
loadMore();
}
});
// Initially load some items.
loadMore();
</script>
</body>
</html>
하지만 보통의 경우에는 한 페이지에 리스트 20개씩 보여지는 페이지를 만들게 되지만, 때때로 스크롤을 내릴경우 다음 페이지의 리스트 20개를 불러오는 기능을 구현해야할 경우가 생긴다.
그때 이 포스팅이 도움이 됐으면 한다.
리스팅할 컨텐츠가 필요하기 때문에 만들어져있는 API를 이용해서 설명하려고 한다.
메인 소스 및 API는 아래 링크를 참고하면 된다.
https://www.javascripttutorial.net/javascript-dom/javascript-infinite-scroll/
먼저 index.html을 생성하고 아래 코드를 넣는다.
* CSS코드는 완성도를 높이고 싶다면 추가하시면 됩니다. 예시에서는 스타일 작업은 하지 않습니다.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript Infinite Scroll - Quotes</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div class="container">
<h1>Infinite scroll tutorial</h1>
<div class="quotes">
</div>
<div class="loader">
<div></div>
<div></div>
<div></div>
</div>
</div>
<script src="js/app.js"></script>
</body>
</html>
App.js에 아래 코드를 기입합니다.
(function () {
const quotesEl = document.querySelector('.quotes');
const loaderEl = document.querySelector('.loader');
// get the quotes from API
const getQuotes = async (page, limit) => {
const API_URL = `https://api.javascripttutorial.net/v1/quotes/?page=${page}&limit=${limit}`;
const response = await fetch(API_URL);
// handle 404
if (!response.ok) {
throw new Error(`An error occurred: ${response.status}`);
}
return await response.json();
}
// show the quotes
const showQuotes = (quotes) => {
quotes.forEach(quote => {
const quoteEl = document.createElement('blockquote');
quoteEl.classList.add('quote');
quoteEl.innerHTML = `
<span>${quote.id})</span>
${quote.quote}
<footer>${quote.author}</footer>
`;
quotesEl.appendChild(quoteEl);
});
};
const hideLoader = () => {
loaderEl.classList.remove('show');
};
const showLoader = () => {
loaderEl.classList.add('show');
};
const hasMoreQuotes = (page, limit, total) => {
const startIndex = (page - 1) * limit + 1;
return total === 0 || startIndex < total;
};
// load quotes
const loadQuotes = async (page, limit) => {
// show the loader
showLoader();
// 0.5 second later
setTimeout(async () => {
try {
// if having more quotes to fetch
if (hasMoreQuotes(page, limit, total)) {
// call the API to get quotes
const response = await getQuotes(page, limit);
// show quotes
showQuotes(response.data);
// update the total
total = response.total;
}
} catch (error) {
console.log(error.message);
} finally {
hideLoader();
}
}, 500);
};
// control variables
let currentPage = 1;
const limit = 10;
let total = 0;
window.addEventListener('scroll', () => {
const {
scrollTop,
scrollHeight,
clientHeight
} = document.documentElement;
if (scrollTop + clientHeight >= scrollHeight - 5 &&
hasMoreQuotes(currentPage, limit, total)) {
currentPage++;
loadQuotes(currentPage, limit);
}
}, {
passive: true
});
// initialize
loadQuotes(currentPage, limit);
})();
이렇게 index.html과 app.js에 코드를 넣고 페이지를 열게되면 아래처럼 덩그러니 페이지가 보여지게 된다.
아마도 이게 뭐지? 하는 생각이 들었을 것이다.
코드는 이상이 없다. 하지만 뭔가 이상한 느낌이 들것이다.
왜냐하면 우리는 infinite scroll이 동작되는것을 보려고 했는데, 페이지 자체에 스크롤이 없다.
따라서 app.js에 선언되어있는 limit 변수를 수정해주어야 한다.
const limit = 10; -- remove
const limit = 20; -- add
20으로 변경해주고 실행하게 되면, 스크롤이 생겨있고, 처음에는 20개의 리스트를 불러온다.
스크롤을 내리게 되면 다음 20개의 리스트 즉 21~40번까지의 리스트를 불러온다.
간단히 살펴봤고, 코드에서 method 부분이나 세세한 설명은 아래 링크를 참고하면 됩니다.
https://www.javascripttutorial.net/javascript-dom/javascript-infinite-scroll/
'Javascript > 배경 & 실무 지식' 카테고리의 다른 글
[JQuery] Ajax (96) | 2024.01.24 |
---|---|
[Javascript] - Slide/Carousel 효과내기 (119) | 2024.01.23 |
[Javascript] Treeview 트리뷰 (4) | 2023.11.27 |
[Javascript] 한국 우편번호,주소 API(다음,카카오) 테스트 (1) | 2023.11.22 |
[Javascript] Ajax 참고자료 (2) | 2023.11.22 |