Home > Web Front-end > CSS Tutorial > How to Make a Div Sticky on Scroll: A Guide to Fixed Positioning and Event Handling?

How to Make a Div Sticky on Scroll: A Guide to Fixed Positioning and Event Handling?

Patricia Arquette
Release: 2024-11-03 07:15:02
Original
523 people have browsed it

How to Make a Div Sticky on Scroll: A Guide to Fixed Positioning and Event Handling?

Sticky Div: Clinging to Screen Top on Scrolling

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.

Solution

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>
Copy after login

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>
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template