Rohan
Rohan

Reputation: 383

How do I change HTML table cell color on click

I'm trying to change the background color of an HTML table cell when the user clicks on the cell. Any ideas on how to do this? I have access to the JS Prototype library, so any suggestions for Prototype or straight Javascript would be welcome.

Upvotes: 5

Views: 31063

Answers (3)

lock
lock

Reputation: 6614

You could loop over all the children of the table and add an click event to them

with prototype the code is:

$('your_table').observe('click', function(event) {
  var clickedCell = event.findElement('td');
  if (clickedCell) {
   clickedCell.setStyle({ background: '#dfd' });
  }
});

Upvotes: 0

Kevin
Kevin

Reputation: 3841

I'm not well versed in the Prototype framework, but here's some raw Javascript that'll do what you're looking for:

var table = document.getElementsByTagName('table')[0];
if(table) table.onclick = function(e) {
    var target = (e || window.event).target;
    if (target.tagName in {TD:1, TH:1})
        target.setAttribute('style', 'background-color: #F00');
};​

Test it on jsFiddle

Upvotes: 0

Larsenal
Larsenal

Reputation: 51146

Ugly, but demonstrates the effect:

  <table>
    <tr>
        <td onclick="this.style.backgroundColor = 'Red';">Sample</td>
        <td onclick="this.style.backgroundColor = 'Blue';">Data</td>
    </tr>
  </table>

Upvotes: 3

Related Questions