function adFollow(fixed_ad,content_container){ var ad_gutter_h = content_container.outerHeight(); var ad_gutter_top = fixed_ad.parent().offset().top; var ad_gutter_bottom = ad_gutter_top + ad_gutter_h; var ad_unit_top = fixed_ad.offset().top; var ad_unit_h = fixed_ad.outerHeight(); var window_pos = $(window).scrollTop(); var window_h = $(window).height(); var followAdH = $(".adContent").height(); if((window_pos >= ad_gutter_bottom - ad_unit_h) && followAdH >= 600){ fixed_ad.css({ "position":"relative", "top": ad_gutter_bottom - ad_gutter_top - ad_unit_h + "px" }); } else if((window_pos >= ad_gutter_top && window_h >= ad_unit_h) && followAdH >= 600){ fixed_ad.css({ "position":"fixed", "top": 0 }); } else { fixed_ad.css({ "position":"relative" }); } } $(window).resize(function(){adFollow($(".ad.sponsored"),$("#slices"));}); $(window).scroll(function(){adFollow($(".ad.sponsored"),$("#slices"));});