resizable-table-2
by Richard Hunter
HTML
<div id="container">
<div class="header">
<div class="left">
property
</div>
<div id="handler" class="handle">
</div>
<div class="right">
value
</div>
</div>
<div id="table" class="table">
<div class="row">
<div class="cell">
alpha
</div>
<div class="cell">
beta
</div>
</div>
<div class="row">
<div class="cell">
alpha
</div>
<div class="cell">
beta
</div>
</div>
<div class="row">
<div class="cell">
alpha
</div>
<div class="cell">
beta
</div>
</div>
</div>
</div>
CSS
body {
padding-left: 100px;
}
#container {
--colWidth: 100px;
}
.header {
display: flex;
}
.left {
background: green;
min-width: 0;
width: calc(100% - (var(--colWidth) + 10px));
}
.handle {
background: limegreen;
width: 10px;
cursor: ew-resize;
}
.right {
background: blue;
overflow: hidden;
width: var(--colWidth);
}
.table {
background: red;
}
.row {
display: grid;
grid-auto-rows: 20px;
grid-template-columns: 1fr var(--colWidth);
gap: 10px;
border-bottom: solid 2px red;
}
.cell {
background: lightblue;
overflow: hidden;
white-space: nowrap;
}
JavaScript
const handlerEl = document.getElementById('handler');
let prevX = -1;
let colWidth = 200;
let containerWidth = 0;
const container = document.querySelector('#container');
function adjustColumns(diff) {
const maxWidth = containerWidth - 10;
colWidth = Math.min(maxWidth, Math.max(0, colWidth + diff));
container.style.setProperty('--colWidth',colWidth + 'px');
console.log(colWidth);
}
function mousemove(event) {
event.preventDefault();
const currentX = event.clientX;
const diff = prevX -currentX;
prevX = currentX;
adjustColumns(diff);
}
const resizeObserver = new ResizeObserver(entries => {
let entry = entries[0];
containerWidth = entry.contentRect.width;
adjustColumns(0);
});
resizeObserver.observe(container);
function mouseup() {
window.removeEventListener('mousemove', mousemove);
prevX = -1;
}
function mousedown(event) {
event.preventDefault();
prevX = event.clientX;
window.addEventListener('mousemove', mousemove);
window.addEventListener('mouseup', mouseup, {
once: true
});
}
handlerEl.addEventListener('mousedown', mousedown);