Search code examples
javascriptcssprototypejs

Floating table headers when container has overflow?


I'm using position:fixed to float some headers in my table when the user scrolls past the top, ala this method: http://css-tricks.com/persistent-headers/

Everything works great on regular pages, but whenever I have a table inside of another div or something with a fixed height and overflow:auto it blows up spectacularly.

What do I need to do to account for not just the page-wide scrolling, but also the scrolling of my container? And to account for scrolling past the 'top' of said container?

Thanks for any direction you guys can point me in.

Here's my existing code:

var mainheader = table.rows[0];
var tableHeight = table.getHeight();
var tableScroll = table.viewportOffset();
var headerHeight = mainheader.getHeight();

// TODO: If we're scrolling a subcontainer, we need to get the offset for that too! Somehow?

// If tableHeight < 1, it means our table his hidden right now, so skip it
if (tableHeight < 1)
    continue;

// If we've scroll down past the very tip top of the table, but haven't yet scroll past the end of it, show our floating headers
if (tableScroll.top < 0 && tableHeight + tableScroll.top - headerHeight > 0)
{
    table.floatingheader.style.display = '';

    // Handle horizontal scrolling too!
    table.floatingheader.style.left = (tableScroll.left + 1) + 'px'; // 1px offset for border
}
else
    table.floatingheader.style.display = 'none';

NOTE: I have access to prototype.js, but do not have jQuery or any other 3rd party library. :/


Solution

  • I realize you're not using jQuery but you may want to look at this guys code on github and see how he implements it, then modify it for your purposes: http://webpop.github.com/jquery.pin/