asdfkjasdfjk asdfkjasdfjk - 6 months ago 22
jQuery Question

Table row background color do not change when using alternate table row

I have a table and it has

class="priority-table"
. And I have the following CSS for alternate row colors and hover colors.

.priority-table tr td{
white-space:nowrap;
}
.priority-table tr:hover{
background-color: #E6E6FA;
}

.priority-table tr:hover:nth-child(even) {
background-color: #E6E6FA;
}

.priority-table tr:nth-child(even) {
background-color: #ffffff;
}

.highlight{
background-color: red;
}


I want to mark a row red when clicked so I added this jQuery

$(".priority-table tr:odd").click(function() {
console.log('first');
$(this).toggleClass("highlight");
});

$(".priority-table tr:even").click(function() {
console.log('second');
$(this).toggleClass("highlight");
});

$(".priority-table tr").click(function() {
$(this).toggleClass("highlight");
});


This only marks even columns red. But I want to keep all columns that I click marked red. How can I do this?

Answer

The following CSS is overriding your red hover on the even rows because it is more specific.

.priority-table tr:nth-child(even) {
    background-color: #ffffff;
}

One way you can get around this is by adding the important attribute to your highlight class, e.g.

.highlight{
  background-color: red !important;
}

Or better still, adding this additional class selector so you have a more specific version of .highlight

.priority-table tr:nth-child(even).highlight{
  background-color: red !important;
}

Lastly, you could remove the ".priority-table tr:nth-child(even)" class if it isn't required.

Example: http://codepen.io/JasonGraham/pen/MeWLbO

Comments