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
DDDOriginal
2024-11-13 14:47:02412browse

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;   
  2. Add a scroll event listener:

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

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

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

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

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!

Statement:
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