JSFiddle - React, Tailwind, and code Playground

by amindunited

HTML

<div class="container">
  <div class="header">
    Header
  </div>
  <div class="menu">
    Menu
  </div>
  <div class="table-container">
  <div class="table-fixed-header">
    
  </div>
    <table>
      <thead class="">
        <tr>
          <th>First</th>
          <th>Last</th>
          <th>Addy</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>1</td>
          <td>toooooooo</td>
          <td>Three</td>
        </tr>
      </tbody>
    </table>
  </div>
  <div class="footer">
    Footer
  </div>
</div>

CSS

* {
  box-sizing: border-box;
}
html, body {
  margin: 0;
  padding: 0;
}
.header {
  background-color: darkviolet;
  color: white;
  font-size: 32px;
  height: 128px;
  padding: 16px;
}
.menu {
  height: 32px;
  background-color: #54c34a;
  padding: 8px 16px;
  font-size: 16px;
}
.footer {
  height: 64px;
  background-color: #d9d9d9;
  padding: 8px 16px;
  font-size: 16px;
}

/**
 * Important Styles
 */
 .container {
   overflow-y: scroll;
   height: 100vh;
   width: 100vw;
 }
 
 .table-fixed-header {
   min-height: 2px;  
 }
 
 table {
   height: 1200px;
   border: solid 1px black;
}
td {
  border: solid 1px black;
}
thead {
  /* position: sticky; */
  /* position: fixed; */
  top: 0px;
  height: 24px;
}
thead.fixed {
  position: fixed;
}

JavaScript

const numRows = 23;
const tbod = document.querySelector('tbody');
for(let i = 0; i < numRows; i++ ) {
tbod.innerHTML += 
	`<tr>
          <td>1</td>
          <td>toooooooo</td>
          <td>Three</td>
        </tr>`;
}

const options = {
  root: null,
  // root: document.querySelector('body'),
  // root: document.querySelector('.container'),
  // rootMargin: `-1px`,
  //threshold: 0.01
  threshold: [0, 0.25, 0.5, 0.75, 1]
};

const thead = document.querySelector('thead');

const onIntersect = (entries) => {
	console.log('on intersect', entries);

  // If intersectionRatio is 0, the target is out of view
  // and we do not need to do anything.
  /* if (entries[0].intersectionRatio <= 0) return */;
  
  if (!entries[0].isIntersecting) {
	  console.log('adding fixed');
  	thead.classList.add('fixed');
  } else {
  	thead.classList.remove('fixed');
  }
};
const intersectionObserver = new IntersectionObserver(onIntersect, options);
// start observing
intersectionObserver.observe(document.querySelector(".table-fixed-header"));