views:

345

answers:

1

Situation: a page with a table with several rows. I want to fix thead when thead reach the top of the page when scrolling, using jquery or any given scripting. I don't want to overflow the table itself. Thank you!

A: 

Here's something that kind of works (quickly tested in FF 3.5, Chrome 3, and IE 8) that you might be able to tailor to your needs.

It uses absolute positioning of the thead. When the thead becomes absolutely positioned, this basically removes it from the original flow of the table and the widths of all the tbody tds adjust accordingly. So you get ugly behavior if you don't specify column widths or if any column's header is wider than any other cell in that column.

CSS

#Grid thead.Fixed
{
    position: absolute;
}

HTML

<table id="Grid">
    <thead>
        <tr>
            <td>A</td>
            <td>B</td>
            <td>C</td>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>1</td>
            <td>2</td>
            <td>3</td>
        </tr>
        <!-- etc. -->
    </tbody>
</table>

jQuery

$(function() {
    var table = $("#Grid");

    $(window).scroll(function() {
        var windowTop = $(window).scrollTop();

        if (windowTop > table.offset().top) {
            $("thead", table).addClass("Fixed").css("top", windowTop);
        }
        else {
            $("thead", table).removeClass("Fixed");
        }
    });
});

I noticed that it does not work in IE unless you specify a strict XHTML doctype:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt;
<html>
    <!-- etc. -->
Lobstrosity
yes, i started using a fixed position, and that ugly behavior took me to ask for a solution here, to save time. by now, yours is the solution! thank you.
egidiocs