Anton Kandybo
Anton Kandybo

Reputation: 4068

How to change table cell background in Javascript

I have such table in HTML:

<table>
    <tr>
        <td>Cell 1</td>
    </tr>
    <tr>
        <td>Cell 2</td>
    </tr>
    <tr>
        <td>Cell 3</td>
    </tr>
</table>

How to change cell's background on mouse move in this cell? If cursor moves away from the cell, background must stay, but if the cursor move to the other cell, it must reset background.

Upvotes: 0

Views: 572

Answers (1)

fcalderan
fcalderan

Reputation:

since you need one cell highlighted, if you're including jQuery you could use this code.

(function() {

   var current_cell;

   $('td').bind('mouseenter', function() {
      if (current_cell) {
         current_cell.removeAttr('id');
      };
      current_cell = $(this);
      current_cell.attr('id', 'highlight');
   });
})();

and then just use a bit of css

td#highlight {
  background: ... ;
}

Upvotes: 1

Related Questions