Reputation: 71
I'm currently using this code:
$(document).ready(function () {
var top = $('#sidebar').offset().top - parseFloat($('#sidebar').css('marginTop').replace(/auto/, 0));
$(window).scroll(function (event) {
// what the y position of the scroll is
var y = $(this).scrollTop();
// whether that's below the form
if (y >= top) {
// if so, ad the fixed class
$('#sidebar').addClass('fixed');
} else {
// otherwise remove it
$('#sidebar').removeClass('fixed');
}
});
});
It sets fixed
on my sidebar when I scroll down after a specific point. I want that my sidebar stops being fixed
after it reaches a point, which could be 200px from the bottom of the whole page. How can I do this?
Upvotes: 3
Views: 4584
Reputation: 59437
You just need to add a few more checks and calculations in your event handler. Here's some revised code that should do what you want:
$(function() {
var top = $('#sidebar').offset().top - parseFloat($('#sidebar').css('marginTop').replace(/auto/, 0));
var footTop = $('#background2').offset().top - parseFloat($('#background2').css('marginTop').replace(/auto/, 0));
var maxY = footTop - $('#sidebar').outerHeight();
$(window).scroll(function(evt) {
var y = $(this).scrollTop();
if (y > top) {
if (y < maxY) {
$('#sidebar').addClass('fixed').removeAttr('style');
} else {
$('#sidebar').removeClass('fixed').css({
position: 'absolute',
top: (maxY - top) + 'px'
});
}
} else {
$('#sidebar').removeClass('fixed');
}
});
});
You can see it in effect at this jsFiddle.
Upvotes: 5
Reputation: 2629
Might not be exactly what you are after, but you could always try the following:
http://imakewebthings.github.com/jquery-waypoints/ (An event can be fired when you scroll to an element)
or
http://plugins.jquery.com/project/whenScrollBottom (Fires event once scrolled near to the bottom, i.e., Twitter or Facebook loading more feed items when you scroll to the bottom of the page)
Upvotes: 0