Home > Web Front-end > CSS Tutorial > How Can I Stop Fixed-Position Scrolling at a Specific Point Using JavaScript?

How Can I Stop Fixed-Position Scrolling at a Specific Point Using JavaScript?

Linda Hamilton
Release: 2024-12-29 06:44:10
Original
196 people have browsed it

How Can I Stop Fixed-Position Scrolling at a Specific Point Using JavaScript?

Stopping Fixed Position Scrolling at a Certain Point

When using elements with fixed positioning, it's possible to have them scroll with the page as the user navigates. However, you may encounter scenarios where you want the fixed element to stop scrolling after reaching a specific point on the page. This can be achieved through JavaScript techniques.

jQuery Solution

One effective approach is to use jQuery:

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

This snippet retrieves the current scroll position of the window using $(window).scrollTop(). It then calculates the distance to keep the fixed element from the top of the page using 250 - $(this).scrollTop(). Finally, it sets the top property of the fixed element (#theFixed) to the calculated distance, ensuring that the element stops scrolling at 250px from the page top.

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