Language/Java Script
JS/무한 스크롤(Infinite scroll)
건담아빠
2022. 7. 29. 08:09
코드를 보시면 아시겠지만 아쉽게도 아직.. jQuery쓰고 IE를 버린지 한달도 안되었다.. OTL.. 당연이 front back이 나눠지지 않았으니 감안해서 보시면 되시겠다.
1. html
<div class="contents-wrap">
<ul class="prd-grid-wrap prd-grid7-wrap" id="divList"></ul>
</div>
2. page script
const TEST = {
page: 1,
limit: 20,
scroll: null,
init: () => {
...
this.scroll = window;
this.load();
...
},
load: () => {
this.getList();
},
getList: () => {
// Infinite 전용 로딩바 show
document.querySelector('#divListLoading').style.display = '';
// ajax 호출
ajax({
...
},
success: (response) => {
$('#divList').append($.parseHTML(TEST.getListHtml(response)));
// 페이징 처리
if (parseInt(response['aParams']['page']) < Math.ceil(parseInt(response['aTotal']['count']) / parseInt(res['aParams']['limit']))) {
TEST.setPageScroll();
}
// Infinite 전용 로딩바 hidden
document.querySelector('#divListLoading').style.display = 'none';
}
...
},
getListHtml: (response) => {
// html return
},
setList: (response) => {
...
// 페이징
TEST.PAGER.draw({
page: parseInt(TEST.page, 10),
limit: parseInt(TEST.limit, 10),
total_count: parseInt(response['total_count'], 10),
});
...
},
/**
* 스크롤시 페이징 처리
*/
setPageScroll: function () {
// 스크롤 이벤트 추가
COMMON.SCROLL.setEvent(TEST.scroll, 10, function () {
TEST.page++;
TEST.getList();
});
}
}
TEST.init();
3. common script
COMMON.SCROLL = {
/**
* 이벤트 추가
*
* @param sScrollSelector
* @param iPlusHeight
* @param callback
*/
setEvent: function (sScrollSelector, iPlusHeight, callback) {
var oScrollContent = $(sScrollSelector);
oScrollContent.off('scroll').scroll(function (e) {
e.preventDefault();
var iScrollBottom = oScrollContent.scrollTop() + oScrollContent.height();
var iScrollHeight = oScrollContent.prop("scrollHeight");
if (sScrollSelector === window || sScrollSelector === document) {
iScrollHeight = $(document).height();
}
if (iScrollBottom + iPlusHeight > iScrollHeight) {
// 스크롤 이벤트 제거
COMMON.SCROLL.offEvent(oScrollContent);
// 조회 호출
callback.apply();
}
});
},
/**
* 이벤트 제거
*
* @param sScrollSelector
*/
offEvent: function (oScrollContent) {
oScrollContent.off('scroll');
}
};