Here is the simple way to create persistent header:
<table class="persist-area" border="1"> <thead> <tr class="persist-header"> <th>Column One Header</th> <th>Column Two Header</th> </tr> </thead> <tbody> <tr> <td>data1</td> <td>data1</td> </tr> <tr> <td>data2</td> <td>data2</td> </tr> <tr> <td>data3</td> <td>data3</td> </tr> <tr> <td>data4</td> <td>data4</td> </tr> <tr> <td>data5</td> <td>data5</td> </tr> </tbody> </table>
Add below styles in your head section
<style> th{ background-color:#CCCCCC; padding:10px; width:200px; text-align:left; } td{ padding:10px; width:200px; } .floatingHeader{ position:fixed; top:0; visibility:hidden; } </style>
And finally, the javascript which makes our job simple
<script src="path to jquery/jquery.min.js"></script> <script> function UpdateTableHeaders() { $(".persist-area").each(function() { var el = $(this), offset = el.offset(), scrollTop = $(window).scrollTop(), floatingHeader = $(".floatingHeader", this) if ((scrollTop > offset.top) && (scrollTop < offset.top + el.height())) { floatingHeader.css({ "visibility": "visible" }); } else { floatingHeader.css({ "visibility": "hidden" }); }; }); } // DOM Ready $(function() { var clonedHeaderRow; $(".persist-area").each(function() { clonedHeaderRow = $(".persist-header", this); clonedHeaderRow .before(clonedHeaderRow.clone()) .css("width", clonedHeaderRow.width()) .addClass("floatingHeader"); }); $(window).scroll(UpdateTableHeaders).trigger("scroll"); }); </script>
No comments:
Post a Comment