JSFiddle - React, Tailwind, and code Playground
HTML
<table style="width:300px" id="mytable">
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
<th>Points</th>
</tr>
<tr>
<td>Jill</td>
<td>Smith</td>
<td>34</td>
<td>50</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>34</td>
<td>94</td>
</tr>
<tr>
<td>John</td>
<td>Doe</td>
<td>34</td>
<td>80</td>
</tr>
</table>
<input type="button" id="mergeme" name="" value="merge">
CSS
table,th,td
{
border:1px solid black;
border-collapse:collapse;
}
th,td
{
padding:5px;
}
.highlighted{
background-color:#999;
}
JavaScript
$(function () {
var isMouseDown = false;
$("#mytable td")
.mousedown(function (e) {
console.log(e.currentTarget.innerHTML);
console.log(e.currentTarget.length);
isMouseDown = true;
$(this).toggleClass("highlighted");
return false; // prevent text selection
})
.mouseover(function (e) {
if (isMouseDown) {
console.log(e.currentTarget.innerHTML);
console.log(e.currentTarget.length);
$(this).toggleClass("highlighted");
}
})
.bind("selectstart", function () {
return false; // prevent text selection in IE
});
$(document)
.mouseup(function () {
isMouseDown = false;
});
});
$("#mergeme").click(function () {
var mylength = $(".highlighted").length;
// Add the colspan of already merged columns
$(".highlighted").each(function(index,el){
if($(el).attr("colspan")>1)
mylength += $(this).attr("colspan") - 1;
});
// Get text from highlighted cells
var alltext = $(".highlighted").text();
// Hide non-first highlighted cells
$("td.highlighted:not(:first)")
.hide()
.toggleClass("highlighted");
// Set text to first highlighted cell, set text, and set colspan
$("td.highlighted:first").attr("colspan", mylength)
.text(alltext)
.toggleClass("highlighted");
});