Saturday, September 25, 2010

gridview header floating/ freezing using Jquery (while scrolling)

You can often see the grid headers floating while scroll down using the browser scroll bar. Previously we used to see the grid header freezing and there are plenty of blogs out there giving valuable information regarding how to freeze the header row. But all these solutions are using a fixed div container and the scroll bar is specific to the grid and not on the browser. Let me attack the problem straight away without any delay.

Problem def: Grid header should float around while the user scroll the browser scroll bar.

Solution ( IN steps)
1. Add the necessary js files for the Jquery to work.(jquery-1.4.3.js)
2. Once the site is using Jquery library then link the js file corresponding to float plugin: (jquery.floatheader.js) you can download this plugin using the following url: http://plugins.jquery.com/project/floatHeader (i have used v1.4.0)
3. i am using a gridview with id "GridView1".
  <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" >
...columns desc....
</asp:GridView>
4. Please note the point that the gridview in default renders the headers ('th' elements) inside <tbody> tag like any other row. In order for our solution to work we need to ensure the header is rendered inside <thead> tag. We will try to achieve this using some jquery trick. The following javascript will give us the floating grid header.
/********function to move header rows under 'thead' element ***********/

function FixGridViewHeaderInsideTHEAD(gridTable) {      
    var jTbl = $(gridTable);  
    if(jTbl.find("tbody>tr>th").length > 0) {
        jTbl.find("tbody").before("<thead><tr></tr></thead>");
        jTbl.find("thead tr").append(jTbl.find("th"));
        jTbl.find("tbody tr:first").remove();
    }
}


/*******jquery ready funtion******

    jQuery(document).ready(function() {
     //  move grid header rows under 'thead' element
     FixGridViewHeaderInsideTHEAD( $("#<%=GridView1.ClientID %>") );
     // register the jquery floater func..
        jQuery('#<%=GridView1.ClientID %>').floatHeader({
       fadeIn: 250,
       fadeOut: 250
        });
    });

Note: This is an alternate approach and not the best in my view , It seems to me that Ricks blog (http://west-wind.com/weblog/posts/822827.aspx) gives a simpler approach which does not use client side scripting.

Please don't forget to check the demo: http://static.slackers.se/pages/javascript/jquery-floatheader/