highlight table row and table cell with jQuery
highlight table row and table cell with jQuery
by Adi Jaya
HTML
<div contenteditable="true" id="editor">
<table class="table">
<tbody>
<tr class>
<td>cell</td>
<td>cell</td>
<td>cell</td>
<td>cell</td>
<td>cell</td>
</tr>
<tr>
<td>cell</td>
<td>cell</td>
<td>cell</td>
<td>cell</td>
<td>cell</td>
</tr>
<tr>
<td>cell</td>
<td>cell</td>
<td>cell</td>
<td>cell</td>
<td>cell</td>
</tr>
<tr>
<td>cell</td>
<td>cell</td>
<td>cell</td>
<td>cell</td>
<td>cell</td>
</tr>
<tr>
<td>cell</td>
<td>cell</td>
<td>cell</td>
<td>cell</td>
<td>cell</td>
</tr>
</tbody>
</table>
</div>
<!-- optional -->
<button id="remove_select_row"> click me = EXAMPLE for Remove highlight </button>
<button id="view-code">view-code</button>
<textarea id="code"></textarea>
CSS
body {
background: white;
margin: 0;
padding: 10px;
border-top: 3px double #656563;
border-left: 3px double #656563;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
#editor {
outline: none;
}
table {
border: none;
border-collapse: collapse;
empty-cells: show;
width: 100%;
font-family: inherit;
font-size: inherit;
margin-bottom: 10px;
cursor: text;
}
table th, table td {
padding: 8px;
vertical-align: middle;
border: 1px solid #dddddd;
}
/* example with background */
.row-active {
background: #f7ffdf;
}
.cell-active {
background: #a6fff3;
}
.row-active .cell-active {
background: #ffffff !important;
outline: 1px solid #00a9ff;
}
textarea#code {
width: 100%;
height: 50%;
outline: none;
resize: none;
margin: 10px auto;
}
JavaScript
//facebook.com/nafis3333
//this for component contenteditable,
//example for insert row above or below
//row
$('td').click(function () { //table className = .table
var $findClass = $('.table').find('.row-active');
var $TR = $('.table tr');
var $parentTR = $(this).parent('tr');
$findClass.removeClass("row-active");
$parentTR.addClass("row-active");
$("tr[class=''],td[class=''],th[class='']").removeAttr('class');
});
//cell
$(function() {
var rows = $('.table tr');
rows.children().click(function() {
rows.children().removeClass('cell-active');
var index = $(this).prevAll().length;
rows.find(':nth-child(' + (index + 1) + ')').addClass('cell-active');
});
});
//optional for remove selecting table row
$('#remove_select_row').click(function () {
var $findClass = $('.table').find('.row-active,.cell-active');
$findClass.removeAttr('class');
});
/* or
$('#editor').blur(function () {
var $findClass = $('.table').find('.row-active,.cell-active');
$findClass.removeAttr('class');
});
*/
//view code
$('#view-code').mousedown(function () {
var $findClass = $('.table').find('.row-active,.cell-active');
$findClass.removeAttr('class');
});
$('#view-code').click(function () {
var html = $('#editor').html();
var code = $('#code');
code.val(html);
});