onscroll 이벤트는 요소의 스크롤바가 스크롤되는 순간 발생하는 이벤트입니다. 사용자가 페이지나 특정 영역을 위아래로 움직일 때마다 이 이벤트가 트리거되며, 이를 활용하면 무한 스크롤, 스크롤 위치 추적, 헤더 고정 같은 다양한 인터랙션을 구현할 수 있습니다.
onscroll 이벤트 기본 문법
onscroll 이벤트는 크게 두 가지 방식으로 등록할 수 있습니다.
- 프로퍼티 방식:
element.onscroll = function() { ... } - addEventListener 방식:
element.addEventListener('scroll', function() { ... })
addEventListener 방식은 여러 개의 핸들러를 등록할 수 있어 더 유연하게 활용됩니다.
예제 코드
아래 예제는 스크롤 가능한 div 박스를 만들고, 사용자가 스크롤하면 메시지가 표시되도록 구현한 코드입니다. 직접 실행해 보면서 onscroll 이벤트의 동작을 확인해 보세요.
<!DOCTYPE html>
<html>
<head>
<style>
div {
border: 2px solid blue;
width: 300px;
height: 100px;
overflow: scroll;
}
</style>
</head>
<body>
<div id="content">
This is demo text. This is demo text.This is demo text.This is demo text.
This is demo text.This is demo text.This is demo text.This is demo text.
This is demo text.This is demo text.This is demo text.
This is demo text.This is demo text.This is demo text.
This is demo text.This is demo text.This is demo text.
</div>
<p id="myScroll"></p>
<script>
document.getElementById("content").onscroll = function() {myFunction()};
function myFunction() {
document.getElementById("myScroll").innerHTML = "Scroll successfull!.";
}
</script>
</body>
</html>코드 설명
- CSS에서
overflow: scroll;속성을 지정해 div 요소에 스크롤바를 생성합니다. document.getElementById("content").onscroll로 해당 요소에 스크롤 이벤트 핸들러를 연결합니다.- 사용자가 스크롤하는 즉시
myFunction()이 호출되어, 아래 단락(#myScroll)에 "Scroll successfull!." 메시지가 출력됩니다.
활용 팁
onscroll 이벤트는 스크롤이 발생하는 동안 매우 짧은 간격으로 수십 번씩 호출될 수 있습니다. 따라서 복잡한 로직을 처리할 때는 쓰로틀링(throttling)이나 디바운싱(debouncing) 기법으로 호출 빈도를 조절하면 성능 저하를 막을 수 있습니다. 또한 window.addEventListener('scroll', ...)를 사용하면 브라우저 창 전체의 스크롤도 감지할 수 있습니다.