freopen
freopen

Reputation: 95

How to align td text to the top of visible part of cell?

My table consists of two column: name of object and object. Name is just one word. Object can occupy several screens. I want to hold name on top of visible part of its cell. In this case when user scrolls page down he can see name of the object until the object is hidden. How can I do this? Are there plugins to do so?

Upvotes: 2

Views: 156

Answers (2)

Etienne Arthur
Etienne Arthur

Reputation: 730

What you are describing, is a persistant header, or a freeze pane like Excel.

Check this link, it's nicelly explained.

Upvotes: 1

Louis Ricci
Louis Ricci

Reputation: 21086

It's only a couple lines of jQuery. http://jsfiddle.net/VuRvs/ Attach a handler to the window scroll event, find your "sticky" heading, position them based on the current scroll position make sure they stay inside of their parent element (the TD).

$(window).on("scroll", function() {
    var y = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
    $(".sticky").each(function() {
        var elm = $(this);
        var td = elm.parent("td");
        var tdTop = td.offset().top;
        var tdBot = tdTop + td.height() - elm.outerHeight();
        if(y <= tdBot && y >= tdTop) {
            // set a placeholder
            if(td.children().length == 1)
                td.append(elm.clone().removeClass("sticky").css("visibility", "hidden"));
            elm.css("position", "absolute");
            elm.css("top", y + "px");
        }
    });
});

Upvotes: 2

Related Questions