Table resize columns
by Greggg
HTML
<div id="editable" contenteditable>
Hello
<table style="width: 100%;">
<tbody>
<tr>
<td style="width: 33.3333%;">
1<br>
</td>
<td style="width: 33.3333%;">
2<br>
</td>
<td style="width: 33.3333%;">
3<br>
</td>
</tr>
<tr>
<td style="width: 33.3333%;">
4<br>
</td>
<td style="width: 33.3333%;">
5<br>
</td>
<td style="width: 33.3333%;">
6<br>
</td>
</tr>
</tbody>
</table>
</div>
<div id="table_resizer"><div></div></div>
CSS
body {
margin: 1em;
}
table {
border: none;
border-collapse: collapse;
empty-cells: show;
max-width: 100%;
}
td {
border: 1px solid #111;
padding: 2px 15px;
vertical-align: middle;
}
#table_resizer {
cursor: col-resize;
background:rgba(255,0,0,.4);/*debug*/
position: fixed;
z-index: 3;
display: none
}
#table_resizer.moving {
z-index: 2
}
#table_resizer div {
-webkit-opacity: 0;
-moz-opacity: 0;
opacity: 0;
-ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";
border-right: 1px solid #1e88e5
}
JavaScript
var min=Math.min, max=Math.max, abs=Math.abs;
var isResizing=false;
var table/*current selected table */, tableRect/*rect of the one selected*/;
var left, right, leftRect, rightRect; /*the td cells being resized*/
$('table').on('mouseenter', function(e){
table = this;
console.log(table);
tableRect=table.getBoundingClientRect();
})
// it's not good to call elements by id directly like below, just for quick dev
table_resizer.addEventListener('mousedown', function(e){
isResizing=true;
});
document.addEventListener('mouseup', function(e){
if (isResizing){
//update cells width
var newWidth=e.clientX-leftRect.left;
var j = left?Array.from(left.parentNode.cells).indexOf(left):0;
console.log('x', left, right);
if (left&&right){
console.log('table resize inner cell ');
for (var i=0;i<table.rows.length;i++){
var leftCell = table.rows[i].cells[j], rightCell = table.rows[i].cells[j+1];
var oldLeftPercent=parseFloat(leftCell.style.width);
var newLeftPercent = newWidth/leftRect.width*oldLeftPercent;
console.log(newWidth, leftRect.width, parseFloat(leftCell.style.width), newLeftPercent, parseFloat(rightCell.style.width), oldLeftPercent-newLeftPercent);
leftCell.style.width = newLeftPercent+'%';
rightCell.style.width = (parseFloat(rightCell.style.width)+oldLeftPercent-newLeftPercent)+'%';
}
}else if(left) {//resizing table
var tableRect=table.getBoundingClientRect();
console.log('table resize left ', e.clientX, tableRect.left, tableRect.width)
table.style.width = parseFloat(table.style.width||100)*(e.clientX-tableRect.left)/tableRect.width+'%';
}else {
var tableRect=table.getBoundingClientRect();
console.log('table resize right ', e.clientX, tableRect.left, tableRect.width); // can only decrease?
table.style.width = parseFloat(table.style.width||100)*(tableRect.right-e.clientX)/tableRect.width+'%';
}
}
...