1

My question is similar to what was asked here regarding keeping a table header fixed to the top of the viewport when scrolled over/past -- except I'm more concerned about the effect it has on the columns (th) within the table header.

In the comments on Andrew Whitaker's answer, there are some interesting suggestions to using jQuery to "fetch" the current width of the table header's columns and setting the fixed table header's columns to those widths.

However, this seems like a lot of heavy lifting especially when I'm already rendering a table within a React application (avoiding jQuery within React). It's a long shot, but has anyone come up with a better implementation?

I suppose I can just fall back to doing what is being done in this fiddle with vanilla JS.

Small snippet of jQuery logic from fiddle^

var tableOffset = $("#table-1").offset().top;
var $header = $("#table-1 > thead");
var $fixedHeader = $("#header-fixed").append($header.clone());

$(window).bind("scroll", function() {
    var offset = $(this).scrollTop();

    if (offset >= tableOffset && $fixedHeader.is(":hidden")) {
        $fixedHeader.show();

        $.each($header.find('tr > th'), function(ind,val){
          var original_width = $(val).width(); // get width value from each
          var original_padding = $(val).css("padding"); // get padding from each
          $($fixedHeader.find('tr > th')[ind])
          .width(original_width)
          .css("padding",original_padding);
        });
    }
    else if (offset < tableOffset) {
        $fixedHeader.hide();
    }
});
Jose
  • 4,880
  • 8
  • 27
  • 49
  • So you need an efficient way (with React) to keep the table headers the same width when you resize the table/window? – davidatthepark Jun 21 '17 at 22:13
  • @davidatthepark More or less. I only brought up React, since I am rendering the table with a component and trying to avoid any kind of DOM manipulation via jQuery, which is what was brought up as an option in that other question I linked. – Jose Jun 21 '17 at 23:06

0 Answers0