Simple Resizable Table

by rajeshpillai

HTML

Click on th and drag...
<table>
    <thead>
        <tr>
            <th>th 1</th>
            <th>th 2</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>td 1</td>
            <td>td 2</td>
        </tr>
    </tbody>
</table>

CSS

table {
    border-width: 1px;
    border-style: solid;
    border-color: black;
    border-collapse: collapse;
}

table td {
    border-width: 1px;
    border-style: solid;
    border-color: black;
}

table th {
    border-width: 1px;
    border-style: solid;
    border-color: black;
    background-color: green;
}

table th.resizing {
    cursor: col-resize;
}

JavaScript

$(function() {
    var pressed = false;
    var start = undefined;
    var startX, startWidth;
    
    $("table th").mousedown(function(e) {
        start = $(this);
        pressed = true;
        startX = e.pageX;
        startWidth = $(this).width();
        start.addClass("resizing");
    });
    
    $(document).mousemove(function(e) {
        if(pressed) {
            $(start).width(startWidth+(e.pageX-startX));
        }
    });
    
    $(document).mouseup(function() {
        if(pressed) {
            $(start).removeClass("resizing");
            pressed = false;
        }
    });
});