Fixed table header on scroll

Hi all

I have a code pen here - https://codepen.io/anon/pen/yKrmOo

I have a table with content above it

When the page scrolls and the table gets to the top of the page I need the table header to be sticky
and the table contents 5to scroll underneath.

I need to keep the table header in its position on top of the table as the table scroll left to right as well

I have made at attempt at the javascript but I’m using a fixed number for the pageYOffset but I dont know what this will be so I need it be when the table reaches the top of the page.

window.onscroll = function() {myFunction()};

var tableHeader = document.getElementById('thead');
var sticky = header.offsetTop;

function myFunction() {
  tableHeader.classList.add("sticky");
  if (window.pageYOffset >= 200) {
    tableHeader.classList.add("sticky");
  } else {
    tableHeader.classList.remove("sticky");
  }
}

That’s not going to work I’m afraid because once you fix position the table header then you lose the relationship between the header and the data. they will no longer match up and arrange as columns.

You would need to get the width of each column and set the width of your fixed header cells to match each column respectively. You would also need to do this on resize because of course the table will be a fluid width and content will re-arrange on smaller/larger screens. This will make it quite ‘janky’ to implement as you test for resize every time the page moves.

Also it is not possible to scroll fixed positioned elements within the viewport unless the items themselves have their own scrollbars.

I gave you the best version in your CSS thread using position:sticky but you wanted to support older browsers so perhaps you should look for an off the shelf plugin as the code is quite complicated to code from scratch. There are many plugins around but you need to check they work on table headers and auto layout tables.

I don’t see any of them working in exactly the same way as position:sticky and think my JS example is one of the better approaches although untested in anything less than IE11.

I will take another look at your example thank you.

I do have another example here that seems to work as I need it to but it does seem jumpy

That’s not working in IE11 anyway :slight_smile:

You’d need to add the transform to the th element instead as IE doesn’t transform thead. Once you do that it will work in IE11 but is indeed extremely jumpy and likely to annoy users or cause epileptic fits.

You could test the code and give position:sticky to modern browsers and just give that that jumpy code to older browsers.

e.g.

Unless you can refine that code to be less jumpy then you are probably better off getting a plugin to do this if you want older browsers support. This one seems to do what you want.

http://mkoryak.github.io/floatThead/

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.