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...
Try this...
$('td').click(function() {
$(this).css('backgroundColor', '#000');
});
...or....
$('table').on('click', 'td', function() {
$(this).css('backgroundColor', '#000');
});
[].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.
$('td').click(function() {
$(this).addClass('active');
);
...or....
$('table').on('click', 'td', function() {
$(this).addClass('active');
});
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()
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With