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:
1 2 3 4 5 6 7 8 |
|
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:
1 2 3 4 |
|
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!