Reputation: 1232
I have implemented datatables on a table in which some rows should have a different background color than others, identified by a CSS class.
I want to change the background color of a row whenever the pointer is hovered over it. For this I am using the following code.
$(document).ready(function () {
oTable = $('#mytable').dataTable({
"bJQueryUI": true,
"sPaginationType": "full_numbers",
"fnRowCallback": function () {
// Assigning colors to inactive rows
$('tr').each(function () {
if ($(this).hasClass('inactive')) {
$(this).css('background', '#fccfcf');
$(this).find('.sorting_1').each(function () {
$(this).css('background', '#fccfcf');
});
}
});
},
"aoColumns": /*3 column table*/
[{
"bSearchable": false,
"bSortable": false
},
null, null]
});
// Dynamically binding hover function to change color and pointer on mouse hover
oTable.$('tr').hover(function () {
previousBackground = $(this).css('background-color');
$(this).css('background-color', '#e2ebff');
$(this).find('.sorting_1').each(function () {
$(this).css('background', '#e2ebff');
});
$(this).css('cursor', 'pointer');
}, function () {
$(this).css('background-color', previousBackground);
$(this).find('.sorting_1').each(function () {
$(this).css('background', previousBackground);
});
});
});
On first load, the table gives the desired result. However when I sort any column, everything falls apart. Some columns display background colors properly, some display only partially. How can I change the background colors without letting the sorting classes affect it?
Upvotes: 0
Views: 6902
Reputation: 51800
Your code only acts on style. You should use CSS to do that.
There is a special :hover
selector in CSS to allow you to change style when the mouse points over an element:
#myTable tbody tr.inactive,
#myTable tbody tr.inactive td.sorting_1 {
background-color: #fccfcf
}
#myTable tbody tr:hover,
#myTable tbody tr:hover td.sorting_1 {
background-color: #e2ebff;
cursor: pointer
}
And drop both your fnRowCallback
and .hover()
callbacks.
Upvotes: 1