Dynamically resizing table with jquery
I am creating a table where someone can enter a width and height, and it
will be rezied to x units ov 16x16 td's
I have gotten it to work mostly properly, problems only arise when I am
increasing the size on the x axis.
(function() {
var src = $('#grid-source');
var wrap = $('<div id="grid-overlay"></div>');
var gsize = 16;
var cols = 32;
var rows = 32;
// create overlay
var tbl = $('<table></table>');
for (var y = 1; y <= rows; y++) {
var tr = $('<tr></tr>');
for (var x = 1; x <= cols; x++) {
var td = $('<td></td>');
td.css('width', gsize+'px').css('height', gsize+'px');
td.addClass('eraser');
tr.append(td);
}
tbl.append(tr);
}
src.css('width', cols * gsize+'px').css('height', rows * gsize+'px')
// attach overlay
wrap.append(tbl);
src.after(wrap);
function setSize(newx, newy) {
var xchange = newx - cols;
var ychange = newy - rows;
if (xchange < 0) {
console.log('reducing x: ' + xchange);
for (var x = xchange; x < 0; x++) {
console.log(x);
$('#grid-overlay table tbody tr').find('th:last,
td:last').remove();
}
}
if (ychange < 0) {
console.log('reducing y: ' + ychange);
for (var y = ychange; y < 0; y++) {
$('#grid-overlay table tbody').find('tr:last').remove();
}
}
if (xchange > 0) {
console.log('increasing x: ' + xchange);
$('#grid-overlay').find('tr').each(function(){
$(this).find('td').eq(-1).after(Array(xchange).join("<td
class='eraser' style='width:16px; height:16px;'></td>"));
});
}
if (ychange > 0) {
console.log('increasing y: ' + ychange);
for (var y = 1; y <= ychange; y++) {
var tr = $('<tr></tr>');
for (var x = 1; x <= newx; x++) {
var td = $('<td></td>');
td.css('width', gsize+'px').css('height', gsize+'px');
td.addClass('eraser');
tr.append(td);
}
tbl.append(tr);
}
}
cols = newx;
rows = newy;
src.css('width', cols * gsize+'px').css('height', rows * gsize+'px');
}
$('#resizeChart').click(function() {
x = $('#inputWidth').val();
y = $('#inputHeight').val();
setSize(x,y);
});
})();
You can find a fully functional example here http://jsfiddle.net/6Ru72/
the questionable block of code is
if (xchange > 0) {
console.log('increasing x: ' + xchange);
$('#grid-overlay').find('tr').each(function(){
$(this).find('td').eq(-1).after(Array(xchange).join("<td
class='eraser' style='width:16px; height:16px;'></td>"));
});
}
if you tinker with the demo, you will see it only increases the width of
the table after a certain point along the y axis. Does anyone have an idea
why this behavior is happening? http://jsfiddle.net/6Ru72/
No comments:
Post a Comment