Teivere Teivere - 4 months ago 18
Javascript Question

How do I change a specific TD's background color on click with JavaScript/jQuery?

I have a

<td style="background-color:white"></td>
.

I want to make it so that when I click inside that
td
, the background-color changes to black. How do I accomplish this with jQuery? Is it onmousedown event or click event?

With normal JavaScript I tried:

<td style="background-color:white" onclick="$(this).onmousedown('background-color','black')">SomeText</td>


...but it didn't work...

Answer

Try this...

jQuery

$('td').click(function() {
   $(this).css('backgroundColor', '#000');
});

...or....

$('table').on('click', 'td', function() {
   $(this).css('backgroundColor', '#000');
});

JavaScript

[].forEach.call(document.getElementsByTagName('td'), function(item) { 
   item.addEventListener('click', function() {
       item.style.backgroundColor = '#000';
   }, false); 
});

...or...

var table = document.getElementsByTagName('table')[0];

var changeStyle = function(e) {
    if (e.target.tagName == 'td') {
        e.target.style.backgroundColor = '#000';
    }
};

table.addEventListener('click', changeStyle, false);

The latter examples only binds one event handler.

It may be better to add a class, so you can specify your styles in a stylesheet and not couple your presentation and behavioural layer.

jQuery

$('td').click(function() {
   $(this).addClass('active');
 );

...or....

$('table').on('click', 'td', function() {
   $(this).addClass('active');
});

CSS

td.active {
  background: #000;
}

The reason this didn't work...

<td style="background-color:white"
     onclick="$(this).onmousedown('background-color','black')">
     SomeText
</td>

...is because there is no onmousedown() event on the jQuery object (though there is mousedown()).

Comments