Leon Gaban
Leon Gaban

Reputation: 39018

How to highlight certain table rows using jQuery?

My CodePen: http://codepen.io/leongaban/pen/nJzcv

So I found this great example of table row highlighting on CSS-Tricks. (Demo)

However I do NOT want to highlight the my top row, I've tried to target only certain td's with a class name, but still not close :(

How would you go about this?

enter image description here

//Row Highlighting
$("table .active").delegate('td','mouseover mouseout', function(e) {
        if (e.type == 'mouseover') {
            console.log('hovering over row');
            $(this).parent().addClass("gray-rollover");
        }
        else {
            $(this).parent().removeClass("gray-rollover");
        }
    });

// Works but highlights all Rows
/*$("table").delegate('td','mouseover mouseout', function(e) {
        if (e.type == 'mouseover') {
            console.log('hovering over row');
            $(this).parent().addClass("gray-rollover");
        }
        else {
            $(this).parent().removeClass("gray-rollover");
        }
    });*/

Upvotes: 0

Views: 1691

Answers (3)

nice ass
nice ass

Reputation: 16709

Why not simply use CSS:

tr:nth-child(even) td {
    background: #333;
    color: #fff;
}

So you want the styles on mouse-over, except the first row. Then:

tr:hover td {
    background: #333;
    color: #fff;
}

tr:first-child:hover td{
    background: none;
    color: #333
}

Or am I missing something here?

Upvotes: 0

Blazemonger
Blazemonger

Reputation: 92893

You might add a table head around the first row and a table body around the rest:

<table cellpadding="12" cellspacing="1" border="1">
  <thead><tr>
    <th>Icon</th>
    <th class="data-td data-name">Name</th>
    <th class="data-td data-career">Career</th>
    <th class="data-td data-company">Company</th>
  </tr></thead>
  <tbody><tr>
  <!-- more stuff -->
  </tr></tbody>
</table>

Then you can just target the table body with your JavaScript:

$("table > tbody .active").on('mouseover mouseout','td', function(e) {

While it's possible to do this with just JS and without altering the HTML, in this case I prefer the HTML change because it's semantically correct -- your first row isn't content, so it should be marked off separately as a header anyway.

Upvotes: 3

dsgriffin
dsgriffin

Reputation: 68586

One way would be to use the not() selector:

$(this).parent().not('tr:first-child').addClass("gray-rollover");

This will add the class to all rows except for the first on mouseover.

CodePen here.

Upvotes: 1

Related Questions