Creating table using pure javascript
by Suraj Raj Shrestha
HTML
<div class="rtype" id="divFiller" priority="1"> <span class="btnClose">x</span>
A</div>
<div class="rtype" id="divBonus" priority="2"><span class="btnClose">x</span>B</div>
<div class="rtype" id="divCross" priority="3"><span class="btnClose">x</span>C</div>
<div class="rtype" id="divNonFixed" priority="4"><span class="btnClose">x</span>D</div>
<div class="rtype" id="divFixed" priority="5"><span class="btnClose">x</span>E</div>
<button id="btnClick">Click me</button>
CSS
.tblFrame {
border: 1px solid green;
}
.tblFrame td {
position:relative;
width: 85px;
height: 110px;
border: 1px solid green;
z-index: 100;
}
.rtype {
display: inline-block;
width: 85px;
height: 110px;
background-color: blue;
margin-top: 10px;
position:relative;
text-align: right;
}
#divFiller {
background-color: #ffeedd;
width: 170px;
height: 220px;
}
#divBonus {
background-color: #abcedf;
width: 170px;
}
#divCross {
background-color: #bbccdd;
height: 220px;
}
#divNonFixed {
background-color: #445566;
}
#divFixed {
background-color: #123456;
}
.btnClose {
background-color: grey;
left: 0;
top: 0;
height:16px;
width: 16px;
display:block;
position:absolute;
padding-bottom: 4px;
cursor:pointer;
}
.btnClose:hover {
background-color: yellow;
color:blue;
}
JavaScript
var canOverlap = false;
var divClone;
var priority = 0;
var numOfRows = 0;
var numOfCols = 0;
var width = 85;
var height = 110;
function tableCreate(row, col) {
var body = document.getElementsByTagName('body')[0];
var tbl = document.createElement('table');
tbl.setAttribute('class', 'tblFrame');
tbl.setAttribute('cellspacing', '0');
tbl.setAttribute('cellpadding', '0');
var tbdy = document.createElement('tbody');
for (var i = 0; i < row; i++) {
var tr = document.createElement('tr');
for (var j = 0; j < col; j++) {
var td = document.createElement('td');
tr.appendChild(td);
}
tbdy.appendChild(tr);
}
tbl.appendChild(tbdy);
body.appendChild(tbl)
}
$('.rtype').on('click', function () {
divClone = $(this).clone();
priority = $(this).attr('priority');
numOfCols = $(this).width() / width;
numOfRows = $(this).height() / height;
});
$('#btnClick').on('click', function () {
tableCreate(3, 3);
});
$(document).on('click', 'td', function () {
var trRows = $(this).closest('table').find('tr').length;
var trCols = $(this).closest('table').find('td').length;
var colsPerRow = $(this).closest('tr').find('td').length;
var x = $(this).closest('tr').index() ;
var y = $(this).index();
if (numOfRows + x <= trRows && numOfCols + y <= colsPerRow) {
if ($(this).find(".rtype").length === 0) {
$(this).append($(divClone));
$(divClone).css({
position: 'absolute',
left: '0px',
top: '-10px',
});
} else {
if ($(this).find('.rtype:last-child').attr('priority') < priority) {
$(this).append($(divClone));
$(divClone).css({
position: 'absolute',
left: '0px',
top: '-10px',
});
} else {
alert("Unable to...