April 7, 2012
Show/hide div on page scroll
Question by santa
I have a table with a lot of rows, which makes the page scroll. There’s some other content above the table. I would like to add a functionality using jQuery, to show div across the page top, as soon as the table scrolls to the point, where the top row disappears above the top border of the screen.
I assume I’ll add a div with position set to fixed, but how do I know when the top row moves above the fold?
<div id="topDiv" style="display: none; position: fixed; top: 0"></div>
<table>
<thead>
<tr>
<th></th>
<tr>
</thead>
<tbody>
<tr>
<td></td>
<tr>
...
</tbody>
</table>
Answer by ckaufman
This is what you are looking for. Sticky Div:
http://blog.yjl.im/2010/01/stick-div-at-top-after-scrolling.html
Implementation example:
http://www.nkhome.com/kestrel/compare-kestrels.php
Answer by Starx
You can use something like this
$(window).scroll(function(e){
$el = $('#topDiv');
if ($(this).scrollTop() > 200 && $el.css('position') != 'fixed'){
$el.css({'position': 'fixed', 'top': '0px'});
}
});
This check if the window has scrolled above 200px and fixes the topDiv