tags:

views:

25

answers:

4

hi, I have a table which has lots of <td></td>. what i want to do is add CSS to the <td> when it got clicked, and remove the CSS from that <td> when user click other <td>, how can i implement that? Thanks.

A: 

Something like:

$('td').removeClass('active')
$(this).addClass('active')

i.e. you remove the active class from all td; then add that class to a specific one.

alamar
I'm assuming this goes goes inside an event handler? -- if so, the first selection `$('td')` is very wasteful (selecting all TDs every time a single TD is clicked, and then removing a class from ALL TDs even though only one of them has the class!?)
J-P
I agree as this was just an example because author didn't specify anything.If the number of TDs is small (less than hundred, I'd say) it's okay.
alamar
A: 
var lastTD;
$('td').click(function(){
    if (lastTD) lastTD.removeClass('some-class');
    lastTD = $(this).addClass('some-class');
});

CSS:

.some-class { color: red; ... }
J-P
it works! thanks.
ohana
* It's fragile.* It creates a global variable it shouldn't.
alamar
A: 
// For click on an element
$('#element_id').click(function() {//or class or any selector
 //change css class
 });
// For outside of an element
$('body').click(function() {
 //change css class
 });
Sadat
A: 

You can do something like event delegation to capture clicks on the entire table and remove the class.

$('#my-table').click(function(event) {
    $(this).find('td').removeClass('clicked');
    var target = $(event.target);
    if (target.is('td')) {
        target.addClass('clicked');
        event.stopPropagation();
    }
});
darkliquid