간단 무한스크롤 예시

Chris·2019년 8월 14일
0

아래로 스크롤시 컨텐츠 목록에 생성되는 간단 무한스크롤 예시이다.
스크롤시 스크롤을 한번을 내려도 두번 발생하기 때문에 스크롤 체크 변수 didScroll를 먼저 선언해 주어야 한다.

css

#productBeforeList {
	height: 600px; 
	border: 1px solid blue;
}
#productScroll {
	height: 200px;
	border: 1px solid red;
}
#productScroll::after {
	content: ''; 
	clear: both; 
	display: table;
}
.product-item {
	float: left; 
	width: 25%; 
	height: 50px; 
	text-align: center; 
	background-color: lightgray; 
	box-sizing: border-box;
}

html

<div id="productBeforeList"></div><!-- 이전 상위 컨텐츠 목록 -->
<div id="productScroll"></div>

js

$(function() {

	// 스크롤 감지
    var didScroll = false;
		
    $(window).on('scroll', function() { didScroll = true; });
    
    setInterval(function() {
        var bottomHeight = $(window).scrollTop() + $(window).height() + 600;
        var docHeight = $(document).height();

        if (didScroll) {
            didScroll = false;
            if (bottomHeight > docHeight) infiniteScrollContent();
        }
    }, 250);
    
    function infiniteScrollContent() {
      
        var scrollcon = '';
        for (var k = 0; k < 4; k++) {
            scrollcon += '<div class="product-item"><strong>상품이름</strong></div>';
        }			
        $("#productScroll").append(scrollcon);
    }
});
profile
올드보이 코더

0개의 댓글