Reputation: 33
First post and new to jQuery. Looked hard but did not find a fully relevant post.
Have alternating row colours in a table; one class NULL/empty one class=alt. jQuery script partially works to highlight the row when clicked.
Question is: how do you use removeClass and then restore (addClass/toggleClass) the specific class that was removed on an onChange event? Any help appreciated. Tks. (See Fiddle below)
HTML
<table id="fooBar" border="0">
<tr>
<th>Text</th>
<th>Text</th>
<th>Text</th>
<th></th>
<th></th>
</tr>
<tr class="">
<td>Text</td>
<td></td>
<td></td>
<td></td>
<td>image</td>
<td>image</td>
</tr>
<tr class="alt">
<td>Text</td>
<td></td>
<td></td>
<td></td>
<td>image</td>
<td>image</td>
</tr>
<tr class="">
<td>Text</td>
<td></td>
<td></td>
<td></td>
<td>image</td>
<td>image</td>
</tr>
<tr class="alt">
<td>Text</td>
<td></td>
<td></td>
<td></td>
<td>image</td>
<td>image</td>
</tr>
</table>
CSS
table {
width:100%;
border-collapse:collapse;
table-layout:auto;
vertical-align:top;
margin-bottom:15px;
border:1px solid #999999;
}
th {
font: bold 11px"Trebuchet MS", Verdana, Arial, Helvetica, sans-serif;
color: #F2EDEB;
border-right: 1px solid #C1DAD7;
border-bottom: 1px solid #C1DAD7;
border-top: 1px solid #C1DAD7;
letter-spacing: 2px;
text-transform: uppercase;
text-align: left;
padding: 6px 6px 6px 12px;
background: #522D25 url(images/bg_header.jpg) no-repeat;
}
tr {
background: #fff;
color: #261F1D;
}
tr:hover, tr.alt:hover {
color: #261F1D;
background-color: #E5C37E;
}
.highlighted {
color: #261F1D;
background-color: #E5C37E;
}
tr.alt {
background: #F5FAFA;
color: #B4AA9D;
}
td {
border-right: 1px solid #C1DAD7;
border-bottom: 1px solid #C1DAD7;
padding: 6px 6px 6px 12px;
}
jQuery
$(document).ready(function () {
$("tr").click(function () {
$(this).closest("tr").siblings().removeClass("highlighted");
$(this).toggleClass("highlighted");
})
});
// Note: currently only works for row without '.alt' css class assigned (ie. empty)
// question is how to replace a class and then RESTORE the class onChange
Here is the jsFiddle: http://jsfiddle.net/codeChaos1988/kh4VY/1/
Also any pointers on best tutorial sites for actually learning to program in javascript/jQuery would be appreciated as well.
Thank you for your help in advance.
Upvotes: 3
Views: 8835
Reputation: 8836
Added this in datatable initialisation section:
"createdRow": function( row, data, index ) {
if (tableInitialized){
flashRow( row );
}
This worked!
Upvotes: -1
Reputation: 783
So that you don't have to worry about removing/restoring the original class, try changing your css to:
.highlighted {
color: #261F1D !important;
background-color: #E5C37E !important;
}
For JS:
$('table').on('click', 'tr', function () {
var state = $(this).hasClass('highlighted');
$('.highlighted').removeClass('highlighted');
if ( ! state) { $(this).addClass('highlighted'); }
});
Upvotes: 11