I have a 3×3 HTML table with each element storing a separate <canvas> element
There is one cell in the table containing text instead of a <canvas>
When a cell containing an image is clicked and the cell to its right contains text, I’m trying to swap that cell’s canvas with the text stored in the neighbouring cell.
With the following code every time I click a cell, the canvas element disappears and only swaps the text, leaving the cell on the right no longer containing text or a <canvas>
I tried accessing the canvas using ("#blankCell").html() but it does not work .. anybody know how to access this content for swapping of values?
I created a simplified jsFiddle for this: http://jsfiddle.net/bobbyrne01/dbMnM/1/
$(function () {
var $tbl = $('<table border="1">').attr('id', 'grid');
var $tbody = $('<tbody>').attr('id', 'tableBody');
var tileCount = 0;
var rowCount = $("#numOfPieces").val();
for (var i = 0; i < rowCount; i++) {
var trow = $("<tr>").attr('id', 'row' + i); // New row
for (var j = 0; j < rowCount; j++) {
$cell.append(canvasArray[tileCount]); // Each data cell contains separate canvas element
$cell.appendTo(trow);
tileCount++;
}
trow.appendTo($tbody);
}
$tbl.append($tbody);
$('table').remove(); // removes previous table if it existed
$('body').append($tbl);
});
$('#grid tr:nth-child(2) td:last').prev().text("empty");
$('#grid tr:nth-child(2) td:last').prev().attr('id', 'blankCell');
Listens for clicks ..
$('body').on('click', '#grid td', function(e) {
var $this = $(this);
if ($(this).closest('td').next("#blankCell").length){
blank = $(this).closest('td').next("#blankCell");
if (blank.length) {
//alert('blank to the right');
$this.before(blank);
}
$(this).attr('id', 'blankCell');
$(this).closest('td').next("#blankCell").attr('id', 'piece');
}
Appreciate any help!
Instead of using canvas elements for swapping, it now only has text.
The goal is if a user selects a cell beside the blankCell I would like to swap that cell with the blankCell, if the user selects a cell not beside blankCell I would like nothing to happen.
Only concerned with left and right detection for now.
Make it simple and just exchange the whole table cells, not their contents or content strings and attributes:
OK, some more complicated code for checking the position included:
Demo at jsfiddle.net