I have an element that is position:fixed and so scrolls with the page how i want it to however. when the user scrolls up I want the element to stop scrolling at a certain point, say when it is 250px from the top of the page, is this possible? Any help or advice would be helpful thanks!
I had a feeling that I would need to use jquery to do so. I tried getting the scrolling or location of the where the user is but got really confused, is there any jquery solutions?
The element is set to 'fixed' or 'relative' depending upon whether the user has scrolled past the element. The element to be stuck is first identified and its current position on the page is calculated. This is done by adding the position of the element relative to the viewport with the current scroll position.
To get or set the scroll position of an element, you follow these steps: First, select the element using the selecting methods such as querySelector() . Second, access the scroll position of the element via the scrollLeft and scrollTop properties.
Do you mean sort of like this?
http://jsfiddle.net/b43hj/
$(window).scroll(function(){ $("#theFixed").css("top", Math.max(0, 250 - $(this).scrollTop())); });
$(window).scroll(function(){ $("#theFixed").css("top", Math.max(0, 100 - $(this).scrollTop())); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div id="theFixed" style="position:fixed;top:100px;background-color:red">SOMETHING</div> <!-- random filler to allow for scrolling --> STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>
Here's a quick jQuery plugin I just wrote that can do what you require:
$.fn.followTo = function (pos) { var $this = this, $window = $(window); $window.scroll(function (e) { if ($window.scrollTop() > pos) { $this.css({ position: 'absolute', top: pos }); } else { $this.css({ position: 'fixed', top: 0 }); } }); }; $('#yourDiv').followTo(250);
See working example →
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With