본문 바로가기

웹 프로그래밍/JavaScript

[JavaScript] 무한 스크롤 구현하기

오늘은 무한 스크롤 구현에 관하여 기록해보겠습니다.

스크롤이 제일 아래로 내려가면 js를 이용하여 새로운 콘텐츠를 생성 및 추가되는 방식으로 구현을 했습니다.

HTML

 

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" type="text/css" href="style.css" />
<title>Infinity Scroll</title>
</head>
<body>
<h1>Infinity Scroll</h1>
<article>
<div class="box">
<p>1번째 블록</p>
</div>
<div class="box">
<p>2번째 블록</p>
</div>
<div class="box">
<p>3번째 블록</p>
</div>
<div class="box">
<p>4번째 블록</p>
</div>
</article>
<script src="Infinity.js"></script>
</body>
</html>
view raw Infinity.html hosted with ❤ by GitHub

section 태그에 class="box"인 div가 있습니다. 현재는 4개의 div가 있지만 스크롤을 내리면 계속 추가되게 할 예정입니다.

 

css

html,
body {
margin: 0;
}
h1 {
position: fixed;
top: 0;
width: 100%;
height: 60px;
text-align: center;
background: white;
margin: 0;
line-height: 60px;
}
article .box {
height: 500px;
padding: 20px;
margin: 10px;
background: white;
border: 1px solid black;
border-radius: 10px;
}
article .box p {
margin: 0;
color: black;
padding: 80px 20px;
}
view raw style.css hosted with ❤ by GitHub

css는 간단하게 h1 태그는 position: fixed를 사용하여 스크롤을 내려도 고정된 위치에서 보이게 하였고 html을 실행하게 되면 기본적으로 보이게되는 스타일은 다음과 같습니다,

 

js

var count = 2;
window.onscroll = function (e) {
/* window.innerHeight = 브라우저에서 실제로 표시되고 있는 영역의 높이
* window.scrollY = 스크롤이 Y축으로 얼마만큼 이동했는지
* document.body.offsetHeight = 요소의 실제 높이
*/
if (window.innerHeight + window.scrollY >= document.body.offsetHeight) {
count++;
var addContent = document.createElement("div");
addContent.classList.add("box")
addContent.innerHTML = `<p>${++count}번째 블록</p>`
document.querySelector('article').appendChild(addContent);
}
}
view raw Infinity.js hosted with ❤ by GitHub

윈도우의 높이와 현재 스크롤 위치의 값을 더한 뒤 문서의 높이와 비교하여 같거나 크다면 콘텐츠를 추가하는 방식입니다.

 

위의 코드들을 실행하여 작성하고 실행해보면 정상적으로 무한스크롤 기능이 작동하는 것을 보실 수 있습니다.