Select cells by dragging

http://stackoverflow.com/questions/2013902/select-cells-on-a-table-by-dragging

by Daehyun Im

HTML

<table cellpadding="0" cellspacing="0" id="our_table">
  <tr>
    <td>a</td>
    <td>b</td>
    <td>c</td>
  </tr>
  <tr>
    <td>d</td>
    <td>e</td>
    <td>f</td>
  </tr>
  <tr>
    <td>g</td>
    <td>h</td>
    <td>i</td>
  </tr>
</table>

CSS

table td {
  width:100px;
  height:100px;
  text-align:center;
  vertical-align:middle;
  background-color:#ccc;
  border:1px solid #fff;
}

table td.highlighted {
  background-color:#999;
}

JavaScript

$(function () {
  var isMouseDown = false;
  $("#our_table td")
    .mousedown(function () {
      isMouseDown = true;
      $(this).toggleClass("highlighted");
      return false; // prevent text selection
    })
    .mouseover(function () {
      if (isMouseDown) {
        $(this).toggleClass("highlighted");
      }
    });
  
  $(document)
    .mouseup(function () {
      isMouseDown = false;
    });
});