11

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...

1
  • I am not sure what you mean by "normal" javascript but your example uses jquery. Commented Apr 29, 2011 at 14:11

3 Answers 3

26

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()).

Sign up to request clarification or add additional context in comments.

5 Comments

Is there a way to do this within the TD tag itself?
@Teivere Yes, you could add the onclick attribute, but it is better to use obtrusive event handlers, e.g. attach them from your JavaScript.
@Teivere - it's a best practice to keep your javascript separate from your HTML
I tried putting this in the head tags, but didnt work, but it did work when I put it in the body tags after the table is written in html. is that a requirement or is there a way to have it work putting the code in the head tags?
That comment should be un-obtrusive event handlers :)
3

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>

See this example on jsFiddle


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>

See this example on jsFiddle

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

2 Comments

I tried putting this in the head tags, but didnt work, but it did work when I put it in the body tags after the table is written in html. is that a requirement or is there a way to have it work putting the code in the head tags?
If you want to put in the head tag use live instead. What happens is that your script element on the head executes before the body is rendered. You can either use live which will bind the event even if the element doesn't exist yet or use $(function(){}) to execute a function when the page is loaded. I will update the answer to be more clear.
3

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.