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

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

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!