Tracking Scroll Positions
In this page:
Reading Window Scroll
Calling $(window).scrollTop() with no argument returns the number of pixels the whole page has been scrolled down from the top. This is the basis for features like showing a 'back to top' button once the user scrolls past a certain point.
Example: Reading Window Scroll
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<div style="height:2000px">Tall content</div>
<script>
console.log($(window).scrollTop());
</script>
</body>
</html>
Reading Element Scroll
scrollTop() also works on individual scrollable elements, not just the window, returning how far that specific element's content has scrolled. This is useful for a scrollable panel or chat box that has its own independent scroll position.
Example: Reading Element Scroll
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<div id="panel" style="height:100px;overflow:auto"><div style="height:500px">Tall inner content</div></div>
<script>
console.log($("#panel").scrollTop());
</script>
</body>
</html>
Setting Scroll Position
scrollTop() can set the vertical scroll position by passing a pixel value, immediately moving the page or element to that position. Combined with jQuery's animate(), this is also how you build a smooth scrolling effect.
Example: Setting Scroll Position
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<div style="height:2000px">Tall content</div>
<script>
$(window).scrollTop(500);
</script>
</body>
</html>
Scroll Events
The scroll event fires whenever a scrollable area -- the window or an individual element -- changes position, letting you react as the user scrolls. Because it can fire very frequently, scroll handlers are often throttled to avoid doing expensive work on every pixel of movement.
Example: Scroll Events
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<div style="height:2000px">Tall content</div>
<script>
$(window).on("scroll", function() {
console.log("Scrolled to", $(window).scrollTop());
});
</script>
</body>
</html>
Scroll to an Element
You can combine an element's offset() coordinates with scrollTop() to move the page so that a specific element comes into view. This is the basic technique behind 'jump to section' links and smooth-scrolling navigation menus.
Example: Scroll to an Element
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<div style="height:1000px"></div>
<p id="target">Target section</p>
<script>
const top = $("#target").offset().top;
$(window).scrollTop(top);
</script>
</body>
</html>
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: