Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Highlighting the clicked row of a striped HTML table

Tags:

javascript

css

Here's an example of my problem on jsFiddle.

I have a table with striped rows imposed by using tr:nth-child(odd) in the CSS, as is done in Twitter Bootstrap for the table-striped class. I want to highlight the most recent clicked row of that table. I do that with the following Javascript:

$('#mytable tbody tr').live('click', function(event) {     $clicked_tr = $(this);     $clicked_tr.parent().children().each(function() {         $(this).removeClass('highlight')     });     $clicked_tr.addClass('highlight'); }); 

That code works fine in a table without striped rows. But with striped rows, the background color of the highlight class won't override the background color of the table-striped class. Why is that? And how can I make it work?

like image 515
dumbmatter Avatar asked Mar 31 '12 01:03

dumbmatter


People also ask

How do you jump a row in HTML?

To add a line break to your HTML code, you use the <br> tag. The <br> tag does not have an end tag. You can also add additional lines between paragraphs by using the <br> tags.


1 Answers

http://jsfiddle.net/iambriansreed/xu2AH/9/

.table-striped class

.table-striped tbody tr.highlight td { background-color: red; } 

... and cleaner jQuery:

$('#mytable tbody tr').live('click', function(event) {     $(this).addClass('highlight').siblings().removeClass('highlight'); });​ 

Update: .live() has since been deprecated. Use .on().

$('#mytable').on('click', 'tbody tr', function(event) {     $(this).addClass('highlight').siblings().removeClass('highlight'); });​ 

Fixed: http://jsfiddle.net/iambriansreed/xu2AH/127/

like image 103
iambriansreed Avatar answered Sep 24 '22 15:09

iambriansreed