ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [JavaScript] 스크롤바 위치감지 이벤트
    JavaScript 2024. 4. 1. 17:27
    반응형

    스크롤바를 이동하여 최상단으로 이동하는 맨위로 버튼이나, 더보기 이벤트를 동작시키기 위해서는

    현재 스크롤바의 위치를 감지하는 로직이 필요하다.

     

    아래 그 예시를 기록으로 남긴다.

    document.body.addEventListener('scroll', () => {
          let isScrollDone = document.body.offsetHeight + document.body.scrollTop >= document.body.scrollHeight ? true : false;
          //총 스크롤 길이보다 스크롤바길이 + 스크롤이동길이가 같거나 크면 스크롤바는 최하단이다.
          if (document.body.scrollTop > 0) {
            if (isScrollDone) {
              this.moreshow = true;
            } else {
              this.moreshow = false;
            }
            //스크롤바가 조금이라도 이동하면 맨위로 버튼 출력
            this.topshow = true;
    	
            let tbody = document.querySelector('.lower-container.table-wrap tbody');
            let listCnt = tbody ? document.querySelector('.lower-container.table-wrap tbody').childElementCount : 0;
            let totalCnt = this.mode === 'user' ? this.totalUserCnt : this.totalWordCnt;
            if (listCnt < totalCnt) {
              this.isLastPage = false;
            }
          } else {
            this.topshow = false;
            this.moreshow = false;
          }
        });

     

    핵심

    **** 스크롤바 길이 + 현재스크롤 위치 >= 전체문서높이 이면 스크롤바는 최하단이다 ****

    스크롤 감지
    document.addEventListener('scroll', ()=>{
    	... 로직
    });
    /*
    스크롤바 길이 구하기 : 스크롤 바를 먼저 최하단으로 이동시킨 후 아래 변수값 체크
        전체 문서 높이 - 스크롤최하단으로 이동한 후의 scrollTop 위치
        **** 스크롤바 길이 + 현재스크롤 위치 >= 전체문서높이 이면 스크롤바는 최하단이다 ****
    */
    let scrollbarlength = document.documentElement.offsetHeight - document.documentElement.scrollTop;
    
    let isScrollDone = scrollbarlength+document.documentElement.scrollTop >= document.documentElement.scrollHeight ? true : false;
    최하단감지변수
    let isScrollDone = document.body.offsetHeight + document.body.scrollTop >= document.body.scrollHeight ? true : false;
    
    // document.body.xxx 정상동작 안할 경우 document.body -> document.documentElement

     

     

     

    반응형

    댓글

Designed by Tistory.