Saturday, May 11, 2024
 Popular · Latest · Hot · Upcoming
9
rated 0 times [  10] [ 1]  / answers: 1 / hits: 30643  / 12 Years ago, mon, december 10, 2012, 12:00:00

I have the header of a table in the middle of a page, but since the page is huge, I want to fix the header to the top of browser while I scroll down for the page...



So my question is: How do I set header to be normal, until the user scrolls down and the top border of header touches the browser border, where it should stay fixed on that position, no matter how much further down the user scrolls?


More From » jquery

 Answers
20

Let me explain as to how this could be done.



Steps




  1. Find your table header, and save its position

  2. Add a listener to the window's scroll event.

  3. Check the window scroll against your table header position

    1. If the position < window scroll - add a class to fix the table header

    2. Else, reset the css to behave like a normal header.




I've posted a fiddle that you can find here.



Code sample



HTML



<div class='lots_of_stuff_in_here'> ... </div>
<table>
<thead id='my_fixable_table_header'>
<tr>
<th>My awsesome header number 1</th>
<th>My awsesome header number 2</th>
</tr>
</thead>
<tbody>
<tr>
<td>Content</td>
<td>Content</td>
</tr>
// much more content
</tbody>
</table>


Javascript



// Just so you get the idea behind the code

var myHeader = $('#my_fixable_table_header');
myHeader.data( 'position', myHeader.position() );
$(window).scroll(function(){
var hPos = myHeader.data('position'), scroll = getScroll();
if ( hPos.top < scroll.top ){
myHeader.addClass('fixed');
}
else {
myHeader.removeClass('fixed');
}
});

function getScroll () {
var b = document.body;
var e = document.documentElement;
return {
left: parseFloat( window.pageXOffset || b.scrollLeft || e.scrollLeft ),
top: parseFloat( window.pageYOffset || b.scrollTop || e.scrollTop )
};
}



[#81514] Friday, December 7, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
stefanicarolinat

Total Points: 145
Total Questions: 91
Total Answers: 93

Location: Cambodia
Member since Thu, Oct 7, 2021
3 Years ago
stefanicarolinat questions
Mon, Nov 15, 21, 00:00, 3 Years ago
Fri, Apr 16, 21, 00:00, 3 Years ago
Thu, Oct 15, 20, 00:00, 4 Years ago
Fri, Jul 17, 20, 00:00, 4 Years ago
;