본문 바로가기

FE/Vanilla

addEventListener scroll 에서 변화량 확인하기

스크롤을 조금만 내렸을 때 특정 위치로 스크롤 되는 코드를 구현해야 해서

다음과 같이 만들었다.

window.addEventlistener('scroll', () => {
	if (window.scrollY > 100 && window.scrollY < 150) {
    	window.scrollTo({
        	top: el.offsetTop,
            behavior: 'smooth',
        });
    }
});

이렇게 했을 때 두가지 문제가 발생했다.

 

첫째는 스크롤을 내렸다가 올라올때에도 이벤트리스너가 실행된다는 것이었고,

두번째는 사파리에서 behavior 속성을 지원하지 않았다.

 

따라서 코드를 다음과 같이 바꾸었다.

let scrollBefore;

const Main = () => {

	...

useEffect(() => {
  smoothscroll.polyfill();
  window.addEventlistener('scroll', () => {
  	const scrollAfter = scrollBefore;
    scrollBefore = window.scrollY
    
    if (scrollAfter < scrollBefore) {
        console.log('down');
    } else {
    	console.log('up');
    }
    
    if (window.scrollY > 100 && window.scrollY < 150 && scrollAfter < scrollBefore) {
      scrollBefore = 0;
      window.scrollTo({
        top: el.offsetTop,
        behavior: 'smooth',
      });
    }
  });
}, []);
};

 

이렇게하여 스크롤이 올라가고 있는 상황인지 내려가고 있는 상황인지 구분할 수 있게 되었다.

 

사파리에서 scrollTo smooth 가 되지 않던 것은 polyfill 을 install 해서 해결했당

https://www.npmjs.com/package/smoothscroll-polyfill

 

smoothscroll-polyfill

Smooth Scroll behavior polyfill

www.npmjs.com

 

는 안된다 개빡친다 시123발 

https://github.com/iamdustan/smoothscroll/issues/157