스크롤 이벤트

위 페이지 처럼 스크롤 시 navbar 가 조절되는 걸 만들어 보자.

window 와 document의 차이

window : 브라우저 탭의 전역 객체

document : window 객체의 속성 (property)

navbar css 추가

main.css
.navbar {
    position: fixed;
    width: 100%;
    z-index: 5;
}

.navbar-brand{
    font-size: 30px;
}

scroll eventListener

  window.addEventListener('scroll', function (){
    console.log(window.scrollY); //Y축 스크롤 
    console.log(window.scrollX); //X축 스크롤 
    console.log(window.pageYOffset);// Y축 스크롤 레거시 
  })
  
  // window.scrollTo(x,y)  //강제로 스크롤 하기 
  // window.scrollBy(x,y)  //현재위치에서 x,y만큼 스크롤 하기 
  
  //jQury 
  
  $(window).on('scroll', function() {
    $(window).scrollTop() // 현재 위치 출력
    $(window).scrollTop(100) // 현재 위치에서 100만큼 이동 
  })

✨ 과제. 스크롤바 100px 내리면 로그 폰트 사이즈 작게 만들기

window.addEventListener('scroll', function (){
    if(window.scrollY > 100){
      $('.navbar-brand').css('font-size', 20);
    }else if(window.scrollY < 100){
      $('.navbar-brand').css('font-size', 30);
    }
})

✨ 과제. 박스 끝까지 스크롤 시 알림띄우기

<div class="lorem" style="width: 200px; height: 100px; overflow-y: scroll">
  Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quae voluptas voluptatum minus praesentium fugit debitis at, laborum ipsa itaque placeat sit, excepturi eius. Nostrum perspiciatis, eligendi quae consectetur praesentium exercitationem.
</div> 

window 스크롤은 배웠는데 아직 div 스크롤은 안배웠음

 // scroll 내린양  +  div 화면에 보이는 높이 == div 실제 높이가 되면 alert 띄워라
 $('.lorem').on('scroll', function(){
    var scroll = document.querySelector('.lorem').scrollTop;
    var height = document.querySelector('.lorem').scrollHeight;
    var realHeight = document.querySelector('.lorem').clientHeight;
    console.log(scroll , height , realHeight);
    
    if(scroll + realHeight >= height){
       alert('정독완료');
    }
 });
    

클라이언트에 따라서 약간의 오차가 있을 수 있음

🔥주의할 점

스크롤 이벤트 리스너 안의 코드는 1초에 60번 이상 실행됨

PC에 부담을 줄 수 있음

바닥체크도 여러번 중복으로 해준다.

오늘 배운걸 활용해서 이런 UI도 만들 수 있다.

Last updated