Can anyone help me pinpoint the issue with my script please?
$(function () {
var top = $(\'#sidebar\').offset().top - parseFloat($(\'#sidebar\').css(\'marginTop\
Ok - many thanks @dark-ashelin
ended up with this - bit of a hack but it works.
$(function () {
var sidebar = $("#sidebar");
var top = $('#sidebar').offset().top - parseFloat($('#sidebar').css('marginTop').replace(/auto/, 0));
var footTop = $('#footer').offset().top - parseFloat($('#footer').css('marginTop').replace(/auto/, 0))-60;
var maxY = footTop - $('#sidebar').outerHeight() - 85;
$(window).scroll(function (evt) {
var y = $(this).scrollTop();
if (y > 100) {
if (y < maxY) {
$('#sidebar').addClass('stickyside').removeAttr('style');
} else {
$('#sidebar').removeClass('stickyside').css({
position: 'absolute',
top: (maxY + 50) + 'px'
});
}
} else {
$('#sidebar').removeClass('stickyside');
}
});
});
The problem is that you are forgetting the margin-top
of your sidebar in your calculation:
var maxY = footTop - $('#sidebar').outerHeight() - 68;
In your Prototype JSFiddle the sidebar just happened to have no margin-top
.
On a sidenote: you may want to cache your selectors to improve performance. If you use the same selector more than once, for example $("#sidebar")
, put it in a variable:var sidebar = $("#sidebar");
.