본문 바로가기
jQuery

[jQuery] 스크롤(scroll) 방향 감지 이벤트

by j. sik 2023. 6. 14.
728x90

제이쿼리(jQuery)를 이용하여 스크롤(scroll) 감지 이벤트 만들기

스크롤 방향에 따라 헤더(header) 숨김/표시 예시

 

[html]

<header>header</header>
<main></main>

 

[css]

header{
  position: fixed;
  width: 100%; height: 100px;
  background: pink;
}
main{
  width: 100%; height: 1000px;
  background: skyblue;
}

 

[js]

let lastScroll = 0; // 초기 스크롤 위치
$(window).scroll(function(){
  let nowScroll = $(this).scrollTop(); // 현재 스크롤 위치
  if (nowScroll > lastScroll) { // 스크롤 위치 증가
    $('header').stop().slideUp(50);
  } else { // 스크롤 위치 감소
    $('header').stop().slideDown(200);
  }
  lastScroll = nowScroll; // 현재 스크롤 위치 할당
});

 

See the Pen [jQuery] scroll _ 스크롤 방향 감지 이벤트 by Jinsik Son (@Jinsik-Son) on CodePen.

728x90