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.
views:
25answers:
4
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
2010-07-10 06:58:00
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
2010-07-10 07:05:28
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
2010-07-10 14:39:15
A:
var lastTD;
$('td').click(function(){
if (lastTD) lastTD.removeClass('some-class');
lastTD = $(this).addClass('some-class');
});
CSS:
.some-class { color: red; ... }
J-P
2010-07-10 07:00:09
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
2010-07-10 07:02:44
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
2010-07-10 07:19:51