I am attempting to adjust the size of a th element without impacting the position of the next th in the row. Specifically, I want the width of the th to influence the width of the next th accordingly, rather than pushing it to the left.
Below is the code that I currently have:
(function () {
var thElm;
var startOffset;
Array.prototype.forEach.call(
document.querySelectorAll("table th"),
function (th) {
th.style.position = 'relative';
var grip = document.createElement('div');
grip.innerHTML = " ";
grip.style.top = 0;
grip.style.right = 0;
grip.style.bottom = 0;
grip.style.width = '5px';
grip.style.position = 'absolute';
grip.style.cursor = 'col-resize';
grip.addEventListener('mousedown', function (e) {
thElm = th;
startOffset = th.offsetWidth - e.pageX;
});
th.appendChild(grip);
});
document.addEventListener('mousemove', function (e) {
if (thElm) {
thElm.style.width = startOffset + e.pageX + 'px';
}
});
document.addEventListener('mouseup', function () {
thElm = undefined;
});
})();
A live demonstration of my code:
(function () {
var thElm;
var startOffset;
Array.prototype.forEach.call(
document.querySelectorAll("table th"),
function (th) {
th.style.position = 'relative';
var grip = document.createElement('div');
grip.innerHTML = " ";
grip.style.top = 0;
grip.style.right = 0;
grip.style.bottom = 0;
grip.style.width = '5px';
grip.style.position = 'absolute';
grip.style.cursor = 'col-resize';
grip.addEventListener('mousedown', function (e) {
thElm = th;
startOffset = th.offsetWidth - e.pageX;
});
th.appendChild(grip);
});
document.addEventListener('mousemove', function (e) {
if (thElm) {
thElm.style.width = startOffset + e.pageX + 'px';
}
});
document.addEventListener('mouseup', function () {
thElm = undefined;
});
})();
table {
table-layout: fixed;
width: 100px;
border-width: 1px;
border-style: solid;
border-color: black;
border-collapse: collapse;
overflow-x: auto;
}
table tr {
box-sizing: content-box;
}
table th {
height: 50px;
width: 20px;
border-width: 1px;
border-style: solid;
border-color: black;
box-sizing: border-box;
user-select: none;
}
<table>
<thead>
<tr style="width: 100%;">
<th style="width: 300px">th 1</th>
<th style="width: 150px">th 2</th>
... // More th elements with varying widths
</tr>
</thead>
</table>
Visit this CodePen link for a demo
Thank you!