How to Make a Div Stick to the Top of the Screen After Scrolling Past It?

Linda Hamilton
Release: 2024-10-31 14:00:02
Original
525 people have browsed it

How to Make a Div Stick to the Top of the Screen After Scrolling Past It?

Anchoring a Div to the Screen Top When Scrolled Past

While developing interactive web pages, it's often desirable to have elements that follow the user's scroll, particularly when reaching specific sections. One such scenario involves a div positioned near the page's top but should "cling" to the screen when scrolled past.

Solution

To achieve this effect, a creative combination of JavaScript and CSS is employed. A position:fixed style is applied to the div, but only after the user scrolls past it.

Here's how to accomplish it:

<code class="javascript">// Cache jQuery objects 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 JavaScript code adds an event handler to the window.scroll event, which monitors the scroll position. When the scroll exceeds the initial position of the div (elTop), a "sticky" CSS class is added to it. This class contains the following CSS styles:

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

As a result, the div assumes a fixed position and stays at the top of the page as long as it remains scrolled past. When the user scrolls back to the top, the sticky class is removed, and the div returns to its original position.

This solution combines the power of JavaScript and CSS to create a responsive and user-friendly experience by keeping important elements within reach, regardless of the page's scroll position.

The above is the detailed content of How to Make a Div Stick to the Top of the Screen After Scrolling Past It?. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!