# 스크롤 이벤트

{% embed url="<https://startbootstrap.com/previews/agency>" %}

{% embed url="<https://startbootstrap.com/previews/freelancer>" %}

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

<figure><img src="https://3814826491-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FJyHOwztPxBT3bLpisjCt%2Fuploads%2FwoofwPKAGtxj08xwmbTW%2FScreenshot_4.png?alt=media&#x26;token=4791ed6f-db74-42af-bbbb-661f70297d73" alt=""><figcaption><p>window 와 document의 차이 </p></figcaption></figure>

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

document : window 객체의 속성 (property)&#x20;

navbar css 추가&#x20;

{% code title="main.css" %}

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

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

{% endcode %}

scroll eventListener

```javascript
  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 내리면 로그 폰트 사이즈 작게 만들기&#x20;

{% code overflow="wrap" fullWidth="false" %}

```javascript
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);
    }
})
```

{% endcode %}

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

```html
<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 스크롤은 안배웠음

```javascript
 // 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('정독완료');
    }
 });
    
```

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

🔥주의할 점&#x20;

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

&#x20;   PC에 부담을 줄 수 있음&#x20;

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

{% embed url="<https://tyle.io/blog/[jquery]-%EC%BB%A8%ED%85%90%EC%B8%A0-%ED%8E%98%EC%9D%B4%EC%A7%80%EC%97%90%EC%84%9C-%EC%8A%A4%ED%81%AC%EB%A1%A4%EC%83%81%ED%83%9C-%ED%91%9C%EC%8B%9C%ED%95%98%EA%B8%B0--progress-indicator>" %}

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