Home > Web Front-end > CSS Tutorial > How to Make a Scrolling Div Stick After Passing it?

How to Make a Scrolling Div Stick After Passing it?

DDD
Release: 2024-11-13 14:47:02
Original
418 people have browsed it

How to Make a Scrolling Div Stick After Passing it?

Making a Scrolling Div Stick

Need to keep a specific div stationary after scrolling past it? Here's how to achieve that using either CSS or jQuery.

CSS-Only Approach

As of recent advancements, CSS alone can accomplish this functionality. More details can be found here: [CSS-Only Fixed Div After Scrolling](https://stackoverflow.com/a/53832799/1482443).

jQuery Approach

If jQuery is acceptable, try this:

  1. Define the initial position of the div:

    var fixmeTop = $('.fixme').offset().top;   
    Copy after login
  2. Add a scroll event listener:

    $(window).scroll(function() {  
    Copy after login
  3. Determine if the scrolled position has passed the initial div position:

    if (currentScroll >= fixmeTop) {
    Copy after login
  4. Apply fixed positioning when scrolled past the div:

        $('.fixme').css({                      
            position: 'fixed',
            top: '0',
            left: '0'
        });
    Copy after login
  5. Reset the positioning when scrolled above the div:

    } else {                                   
        $('.fixme').css({                      
            position: 'static'
        });
    }
    Copy after login

For a more comprehensive understanding, check out this live example: [jQuery Fixed Div After Scrolling](http://jsfiddle.net/5n5MA/2/).

The above is the detailed content of How to Make a Scrolling Div Stick After Passing 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template