How to Make a Div \'Stick\' to the Top of the Page on Scroll?

Patricia Arquette
Release: 2024-11-03 21:03:03
Original
213 people have browsed it

How to Make a Div

Position Div at Screen Top on Vertical Scrolling

Question:

How can I make a div "stick" to the top of a webpage when a user scrolls past it? After returning to the page's top, I want the div to restore to its original position.

Solution:

The key to this functionality is setting position: fixed on the div only after the user has scrolled past it. To achieve this, we can use a handler attached to the window.scroll event:

<code class="javascript">// Cache selectors for improved performance
var $window = $(window),
    $stickyEl = $('#the-sticky-div'),
    elTop = $stickyEl.offset().top;

$window.scroll(function() {
    $stickyEl.toggleClass('sticky', $window.scrollTop() > elTop);
});</code>
Copy after login

This code adds a sticky CSS class to the div when the page scrolls past it and removes the class when the page returns to the top. The CSS class is defined as:

<code class="css">#the-sticky-div.sticky {
    position: fixed;
    top: 0;
}</code>
Copy after login

When the sticky class is added, the div will assume a fixed position and remain at the top of the screen. It will return to its original position when the class is removed.

Note: The code has been optimized to cache jQuery objects for improved performance.

The above is the detailed content of How to Make a Div \'Stick\' to the Top of the Page on Scroll?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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