웹개발 및 최신 테크 소식을 전하는 블로그, 웹이즈프리

HOME > js

자바스크립트 현재의 스크롤바 위치 가져오는 방법

Last Modified : 2020-03-19 / Created : 2019-03-08
54,985
View Count
자바스크립트를 사용하여 현재의 스크롤바 위치값을 가져오는 방법입니다. 어떻게 하면 스크롤바 값을 가져오는지 아래에서 알아봅니다.




# 자바스크립트에서 스크롤 위치 값 가져오기

스크롤바의 위치를 가져오는 방법은 몇 가지가 존재합니다. 그 중 몇 가지를 알아보면 다음과 같습니다.

window.scrollY
document.scrollingElement.scrollTop

document.documentElement.scrollTop
document.querySelector('html').scrollTop


위 방법들 모두 현재 스크롤바의 위치를 숫자로 반환합니다. 다만 위의 두 가지 방법은 IE에서 동작하지 않습니다.
// IE not supports
window.scrollY;
document.scrollingElement.scrollTop;

// Supports all major browsers
document.documentElement.scrollTop;
document.querySelector('html').scrollTop;

그럼 아래에서 간단한 예제를 사용하여 알아봅니다.


! 스크롤 위치 가져오기 예제 보기

만약 현재 스크롤바가 제일 상단이라면 0을 반환할 것입니다.
var scrollPosition = window.scrollY || document.documentElement.scrollTop;
console.log(scrollPosition);


0  //  맨 위 상단인 경우 0 반환

앞에 언급한 것 처럼 IE 브라우저의 경우 window.scrollY의 프로퍼티가 존재하지 않습니다. 이 경우 document 하위의 documentElement를 사용하며 scrollTop을 사용해야합니다.
document.documentElement.scrollTop;

그래서 크로스브라우징을 위해서 window.scrollY || document.documentElement.scrollTop 방법을 사용했습니다.
var _scrollTop = window.scrollY || document.documentElement.scrollTop;


console.log(_scrollTop)

이제 IE 및 대부분의 브라우저에서 현재 스크롤위치를 반환하게 됩니다.

Previous

자바스크립트 형제 요소 중 몇 번째인지 인덱스 값 얻기, index

Previous

자바스크립트 fetch API 알아보기