dynamic event replace TD or TH - jquery
dynamic event replace TD or TH - jquery
by Adi Jaya
HTML
<table contenteditable>
<tr>
<th>## TH ##</th>
<th>## TH ##</th>
<th>## TH ##</th>
</tr>
<tr>
<td>## TD ##</td>
<td>## TD ##</td>
<td>## TD ##</td>
</tr>
</table>
<button class="disabled" id="replace_to_th">Replace to TH</button>
<button class="disabled" id="replace_to_td">Replace to TD</button>
CSS
body {
font-family :arial;
}
[contenteditable]{
outline : none;
}
table {
border: none;
border-collapse: collapse;
empty-cells: show;
width: 100%;
font-family: inherit;
font-size: inherit;
margin-bottom: 10px;
}
table th, table td {
padding: 8px;
min-width: 25px;
vertical-align: middle;
border: 1px solid #dddddd;
}
th {
background: #5cb796;
color: #f3f3f3;
}
td {
background: #feffca;
color: black;
}
.disabled {
pointer-events: none;
opacity: .5;
}
.selected {
outline:1px solid red;
}
JavaScript
//libs jquery 3.2.1
//facebook.com/nafis3333
$("table").click(function(e) {
var e = $( event.target );
if ( e.is( "td" ) ) {
// disabled or not
$("#replace_to_th").removeClass('disabled');
$("#replace_to_td").addClass('disabled');
$(document).find('.selected').removeClass('selected');
e.addClass('selected');
//event click, great mode with add class mousemove
$("#replace_to_th").bind('click', function() {
$('td.selected').replaceWith(function() {
return $('<th/>', { html: this.innerHTML});
});
});
}
if (e.is("th")) {
$("#replace_to_td").removeClass('disabled');
$("#replace_to_th").addClass('disabled');
$(document).find('.selected').removeClass('selected');
e.addClass('selected');
//event click, great mode with add class mousemove
$("#replace_to_td").bind('click', function() {
$('th.selected').replaceWith(function() {
return $('<td/>', { html: this.innerHTML});
});
});
}
});