Home >Web Front-end >CSS Tutorial >How to Make a Div Sticky on Scroll: A Guide to Fixed Positioning and Event Handling?
Imagine having a div positioned close to the page top with crucial buttons or controls. As the user scrolls vertically, you want this div to follow them, clinging to the screen's top. Upon returning to the top, it should resume its original location.
The key to achieving this behavior is to make the div "sticky" only after the user scrolls it past the viewport. This involves setting its CSS position to fixed. Here's how to implement it:
<code class="javascript">// Cache jQuery objects for efficiency. const $window = $(window); const $stickyEl = $('#the-sticky-div'); const elTop = $stickyEl.offset().top; $window.scroll(function() { $stickyEl.toggleClass('sticky', $window.scrollTop() > elTop); });</code>
This code attaches an event handler to the window's scroll event. When triggered, it checks if the current scroll position has exceeded elTop (the div's initial offset from the top). If true, it adds a CSS class named sticky to the div, causing it to become fixed at the screen's top. Otherwise, it removes the class, allowing the div to return to its original position.
The corresponding CSS class definition would look like this:
<code class="css">#the-sticky-div.sticky { position: fixed; top: 0; }</code>
The above is the detailed content of How to Make a Div Sticky on Scroll: A Guide to Fixed Positioning and Event Handling?. For more information, please follow other related articles on the PHP Chinese website!