Fixing / Unfixing Div When Scrolling
Basically i have 4 divs (a Banner, left content, right content, and a footer). The banner and left content divs are fixed while the right content and footer are not. What I'd like
Solution 1:
Here are some general steps to do this:
- Use Javascript to get the pixel positions of the
div
and footer - Using the
onscroll
listener, listen for when the footer should "unfix" - When that happens, use
className
to add a class"fixed"
to the footer
In your CSS, you should add:
.fixed { position: fixed; }
Using jQuery would make all of this easier, too.
Hope that helps!
Solution 2:
I forked the Fiddle: http://jsfiddle.net/YK72r/2/
What I did is called an if
on every scroll event, used a bit of metrics math to find the height needed, changed the css of the left sidebar using jQuery's css
method, and then added an else
statement to revert it when scrolling back up.
var scrollHeight;
$(window).ready(function() {
scrollHeight = $('#footer').offset().top - $('#left').height() - $('#left').offset().top;
});
$(window).scroll(function() {
if ($(document).scrollTop() >= scrollHeight) {
$('#left').css({
'position': 'relative',
'margin-top': '350px'
});
} else {
$('#left').css({
'position': 'fixed',
'margin-top': '100px'
});
}
});
Note that I changed the heights a bit, so mind the css pixel values.
Solution 3:
Try this:
$(window).scroll(function () {
var ftop = $("#footer").position().top;
var lbottom = $("#footer").position().top + $("#left").height();
var scrollTop = $(window).scrollTop();
var diff = ftop - scrollTop;
if( diff <= lbottom)
$("#left").css("position","static");
else
$("#left").css("position","fixed");
});
Post a Comment for "Fixing / Unfixing Div When Scrolling"