Home > Web Front-end > CSS Tutorial > How to Stop Scrolling a Fixed-Position Element at a Specific Point Using jQuery?

How to Stop Scrolling a Fixed-Position Element at a Specific Point Using jQuery?

Patricia Arquette
Release: 2024-12-18 19:23:09
Original
803 people have browsed it

How to Stop Scrolling a Fixed-Position Element at a Specific Point Using jQuery?

How to Halt Scrolling at a Fixed Position

You want an element with fixed positioning to scroll with the page until it reaches a specific point (e.g., 250px from the page top), after which it should stop scrolling. Let's delve into a solution using jQuery.

jQuery Implementation

The following code achieves what you're aiming for:

$(window).scroll(function() {
    $("#theFixed").css("top", Math.max(0, 250 - $(this).scrollTop()));
});
Copy after login

In this code:

  • $(window).scroll(function() { ... }) binds an event listener to the window's scroll event.
  • When the page is scrolled, the code calculates the new position for the element with the ID #theFixed.
  • Math.max(0, 250 - $(this).scrollTop()) ensures that the element doesn't go above 0px or below 250px from the top of the page.
  • $(#theFixed).css("top", ...) sets the new top position for the fixed element.

Implementation Example

The following fiddle demonstrates how it works:

[JS Fiddle](insert fiddle URL here)

The above is the detailed content of How to Stop Scrolling a Fixed-Position Element at a Specific Point Using jQuery?. 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