
현재 Scroll 위치 파악 후, 직전 Scroll 위치값과 비교해서 forward, backward 판단
let lastScrollY = window.scrollY;
window.addEventListener('scroll', () => {
let currentScrollY = window.scrollY;
if (currentScrollY > lastScrollY) {
// 스크롤 다운 상태
console.log('스크롤 다운');
} else if (currentScrollY < lastScrollY) {
// 스크롤 업 상태
console.log('스크롤 업');
}
lastScrollY = currentScrollY;
});
생성자 함수에
lastScrollTop변수 정의this.lastScrollTop = 0; // 바로 이전(마지막) 스크롤 위치
> ### 즉, `lastScrollTop`이 더 작으면 => 스크롤을 내렸다!! 고 판단
```js
window.addEventListener('scroll', () => {
// 앞 내용은 생략...(init 함수 내용과 같음..)
console.log('lastScrollTop: ' + this.lastScrollTop);
console.log('scrollY: ' + scrollY);
this.lastScrollTop = scrollY; // 마지막으로 스크롤한 위치 저장
});

.character[data-direction='forward'] {
transform: rotateY(180deg);
}
.character[data-direction='backward'] {
transform: rotateY(0deg);
}
init() {
window.addEventListener('scroll', () => {
clearTimeout(this.scrollState);
// 스크롤시 timeId라는 숫자를 리턴하니까 => true임
if (!this.scrollState) {
this.mainElm.classList.add('running');
// console.log('running 클래스 붙었음');
}
this.scrollState = setTimeout(() => {
this.scrollState = null; // 스크롤 멈춤 상태
this.mainElm.classList.remove('running'); // 시각적으로도 멈추게끔 클래스 remove
}, 500);
// 이전 스크롤 위치 비교
if (this.lastScrollTop > scrollY) {
// 이전 스크롤위치가 크다면, 스크롤 올림
this.mainElm.setAttribute('data-direction', 'backward');
} else {
// 현재 스크롤 위치가 크다면, 스크롤 내림
this.mainElm.setAttribute('data-direction', 'forward');
}
this.lastScrollTop = scrollY;
});
}
}