How to Resize a HTML table using Jquery?


Do you want to learn how to re-size a HTML table using Jquery? Usually in HTML we can not re-size a table but we can do this using Jquery methods mousedown(),mousemove(),mouseup(). Read more to find the Jquery script for resizing a table.

In normal HTML we can not re-size table. That means we can not drag the table for re-size.

If we use the Jquery methods and some CSS classes we can do this kind of scenario. Let us see how to do that.

First of all we will take a normal HTML table code it like this below.



<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>


Next we can go to the Jquery coding for drag and re-size the HTML table.
In Jquery we have three mouse methods. Those are
1.mousedown()
2.mousemove()
3.mouseup().

1.mousedown(): This method will fire when mouse click is entered ( mouse left button clicked holding).

2.mousemove(): This method will fire when mouse cursor is moving.

3.mouseup(): This method will fire when mouse click is left out( mouse left button clicked leaving).

So using these above methods i will write a Jquery code. it is like this below code.

$(document).ready(function()
{
var clicked = false;
var th= undefined;
var thX, thWidth;

$("table th").mousedown(function(e) {

th = $(this);
clicked = true;
thX = e.pageX;
thWidth = $(this).width();
$(th).addClass("resize");
});

$(document).mousemove(function(e) {
if(clicked) {
$(th).width(thWidth+(e.pageX-thX));
}
});

$(document).mouseup(function() {
if(clicked) {
$(th).removeClass("resize");
clicked= false;
}
});
});

and we will apply this below css for dragging cursors and colors of the table

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

}

table td {
border-width: 1px;
border-style: solid;
border-color: darkgray;
padding:5px;
}

table th {
border-width: 1px;
border-style: solid;
border-color: darkgray;
background-color: silver;
padding:5px;
cursor:pointer;
}

table th.resize {
cursor: e-resize;
}


Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: