Sticky / Persistent Headers
June 15th, 2013 | Javascript , Jquery
<div class="sticky-list"> <ul class="sticky-ul"> <li> <h3 class="title">Section Headline 0</h3> <ul> <li>Content line 0</li> <li>Content line 1</li> <li>Content line 2</li> <li>Content line 3</li> <li>Content line 4</li> </ul> </li> <li> <h3 class="title">Section Headline 1</h3> <ul> <li>Content line 0</li> <li>Content line 1</li> <li>Content line 2</li> <li>Content line 3</li> <li>Content line 4</li> </ul> </li> <li> <h3 class="title">Section Headline 2</h3> <ul> <li>Content line 0</li> <li>Content line 1</li> <li>Content line 2</li> <li>Content line 3</li> <li>Content line 4</li> </ul> </li> <li> <h3 class="title">Section Headline 3</h3> <ul> <li>Content line 0</li> <li>Content line 1</li> <li>Content line 2</li> <li>Content line 3</li> <li>Content line 4</li> </ul> </li> </ul> </div>
ul { list-style: none; margin: 0; padding: 0; } h3 { background: #fff; margin: 0; } .sticky-list { height: 160px; position: relative; overflow: hidden; width: 200px; margin: 20px auto; } .sticky-ul { height: 100%; overflow: auto; padding-top: 20px; } .sticky { position: absolute; top: 0; }
$(".sticky-ul").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") } }); }); });