Reputation: 317
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...
Upvotes: 11
Views: 74621
Reputation: 490637
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()
).
Upvotes: 26
Reputation: 3215
I think jquery may be overkill here. You can just use something like this.
<table>
<tr>
<td onclick="javascript:this.style.background = '#000000';">this</td>
</tr>
</table>
You can play with it here - http://jsfiddle.net/yVvyg/
This can also bedone from the head tag
loadtheclicks() {
var ar = document.querySelectorAll("td"); //could also use getElementByTagname
for (var i=0; i< ar.length; i++) {
ar[i].addEventListener("click", function() { this.style.background = '#000000'; }, false);
}
}
Just call that onload and you should be gold. I have that on jsfiddle as well - http://jsfiddle.net/2anSz/4/
Upvotes: 3
Reputation: 100381
The correct function is mousedown. But you can just use a click.
<table> ... </table>
<script>
$("table tr td").click(function() {
$(this).css("background", "#fff");
});
</script>
It is recommended that your script is not mixed with HTML, but this is valid:
<table>
<tr>
<td onclick="$(this).css('background', '#fff')">change color</td>
</tr>
</table>
Your onclick event was trying (incorrect syntax) to bind an event on itself and it wasn't changing the element style.
This example shows why the same script on the head doesn't work.
.bind
or .click
will bind to existing elements, live
will bind on any element, even if it is inserted afterwards.
jQuery references
Upvotes: 3