이번 시간에는 무한 스크롤을 만들어보도록 하겠습니다. 무한 스크롤이란 포스팅이 많아지면 Ajax 통신을 이용해 페이지를 계속 로드하는 것을 말합니다.
post_list.html
에서 'page'를 검색하시면 'page'라는 id를 가진 input 태그가 하나 있습니다. 여기에다가 Ajax 통신을 이용해서 article을 계속해서 추가할 것인데요. input 박스를 article 아래 넣도록 하겠습니다.
파일명 : post/templates/post/post_list.html
{% for post in posts %}
<article class="contents">
...
</article>
{% endfor %}
**<div id="post_list_ajax"></div>** <!--post를 계속해 추가하는 코드-->
**<input type="hidden" id="page" value="2">**
Ajax 통신을 하는 script_ajax.html
을 수정하겠습니다. 프로트엔드 수업을 듣고 오셔서 알고 계시겠지만 전체 페이지에 두 가지의 JavaScript 기능이 들어가 있습니다. 사이트의 사이즈가 줄어들었을때 사이드 박스의 위치를 잡아주는 부분, 스크롤을 내렸을 때 헤더부분 로고가 없어지는 부분입니다.두기능을 먼저 작성하고 스크롤에서 Ajax 통신을 시도하겠습니다.
파일명 : post/templates/post/script_ajax.html
<script type="text/javascript">
(function(){
const delegation = document.querySelector('.contents_box');
**const side_box = document.querySelector('.side_box');**
**const header = document.querySelector('#header');**
function delegationFunc(e){
...
}
**function resizefunc(){**
**console.log('리사이즈')**
**if(pageYOffset >= 10){**
**let calcWidth = (window.innerWidth * 0.5) + 167;**
**if(side_box){**
**side_box.style.left = calcWidth + "px";**
**}**
**}**
**}**
**function scrollfunc(){**
**var scrollHeight = pageYOffset + window.innerHeight;**
**var documentHeight = document.body.scrollHeight;**
**console.log(pageYOffset);**
**console.log('scrollHeight:'+scrollHeight);**
**console.log('documentHeight:'+documentHeight);**
**if (pageYOffset >= 10){**
**header.classList.add('on');**
**resizefunc();**
**if(side_box){**
**side_box.classList.add('on');**
**}**
**}**
**else {**
**header.classList.remove('on');**
**if(side_box){**
**side_box.classList.remove('on');**
**side_box.removeAttribute('style');**
**}**
**}
}**
****// 뷰의 크기가 변할 때 resizefunc 함수 실행
**window.addEventListener('resize', resizefunc);**
// 스크롤이 이동했을 때 scrollfunc함수를 실행
**window.addEventListener('scroll', scrollfunc);**
****delegation.addEventListener('click',delegationFunc);
})()
</script>
전체 페이지의 크기를 줄이시면 개발자 도구 콘솔 창에 **'리사이즈'**라고 출력하는 것을 보실 수 있습니다.
스크롤을 내리시면 개발자 도구 콘솔 창에 scrollHeight, documentHeight가 출력되시는 것을 확인할 수 있습니다.