$(".sticky-list").each(function () { var cname = "sticky"; var v = $(".title"); var h = v.outerHeight(); v.eq(0).addClass(cname); $(this).scroll(function () { v.each(function () { var t = this; var top_of_container = $(t).scrollTop(); var top_of_object = $(t).position().top; if (top_of_container > top_of_object) { v.removeClass(cname).css("top", "auto"); $(t).addClass(cname).css("top", 0); } else if ((top_of_container > top_of_object - h) && top_of_container - top_of_object < 0) { $("." + cname).css("top", top_of_object - top_of_container - h + "px") } }); }); });