16 points · by unalone · 17y ago · 10 comments
What I'm looking to do is create a div that moves along with the user's scrolling - exactly how a fixed div does - but that only does so within the confines of a certain space. I have a site design that's split into two pieces. I want the div to move within the top space, stop when it gets to the bottom space. After that it quits moving down.
How would I get this to work? The problem is, I'm not at all familiar with using JavaScript to manipulate physical location, so I'm not certain how exactly I'd make this solution. And, to the best of my knowledge, this isn't something that HTML/CSS can do on its own: fixed is all-or-nothing.
$(window).scroll(function() {
var offsetTop = $(window).scrollTop();
$("#target").css({top: offsetTop});
});
To explain, whenever the viewport is scrolled, the offset of the viewport to the top of the page is set (offsetTop). Then the #target element is moved to follow the viewport. That will give a fixed effect, so what you need to do is set the max offsetTop to (max depth - #target height).Note: Dimension type calculations vary widely among browsers, so using a library like jQuery dimensions is quite helpful.
I love jQuery.
var attrs = {};
$(document).ready(function(){
attrs.startY = $("#target").offset().top;
// pad the bottom by 20 pixels including the 20 pixels from top added in fixed()
attrs.endY = $('#bottom').offset().top - $("#target").height() - 40;
var t = null;
$(window).scroll(function(){
clearTimeout(t);
t = setTimeout('fixed()', 500);
});
});
function fixed() {
var offsetTop = $(window).scrollTop();
if (offsetTop < attrs.startY) {
offsetTop = attrs.startY-20; // get rid of 20 pixel padding when at the top
} else if (offsetTop > attrs.endY) {
offsetTop = attrs.endY;
}
$("#target").animate({top: offsetTop+20}, 500); // add 20 pixel padding from the top
}