$(function() { var top = $('#sidebar').offset().top - parseFloat($('#sidebar').css('marginTop').replace(/auto/, 0));; var top2 = $('#sidebar2').offset().top - parseFloat($('#sidebar2').css('marginTop').replace(/auto/, 0)); var footTop = $('.speakerBreafProfile').offset().top - parseFloat($('.speakerBreafProfile').css('marginTop').replace(/auto/, 0)); var footTop2 = $('.sidebarFixedDiv').offset().top - parseFloat($('.sidebarFixedDiv').css('marginTop').replace(/auto/, 0)); var maxY = footTop - $('#sidebar').outerHeight(); var maxY2 = footTop2 - $('#sidebar2').outerHeight(); $(window).scroll(function(evt) { var y = $(this).scrollTop(); if (y > top || y > top2) { if (y < maxY || y < maxY2) { $('#sidebar').addClass('fixed').removeAttr('style'); $('#sidebar2').addClass('fixed2').removeAttr('style'); } else { $('#sidebar').removeClass('fixed').css({ position: 'absolute', width: '22.9%', top: ((maxY - top) + 120) + 'px' }); $('#sidebar2').removeClass('fixed2').css({ position: 'absolute', width: '22.9%', top: ((maxY2 - top2) + 300) + 'px' }); } } else { $('#sidebar').removeClass('fixed'); $('#sidebar2').removeClass('fixed2'); } }); });