I currently have a html table (with 2 columns) and I am trying to add various effects to this table such as table row hover effect, table click effect, etc…This is the script I am using now and its working fine so far:
<head>
<script type="text/javascript">
$(document).ready(function(){
//the following script is to change the table row bg color when clicked
$('tr').click(function(){
$('tr td').css({ 'background' : 'none'});
$('td', this).css({ 'background-color' : '#CCC' });
});
//the following script is for the table row hover effect
$('tr').hover(function() {
$(this).css('background-color', '#FFFF99');
},
function() {
$(this).css('background-color', '#FFFFFF');
$(this).contents('td').css('border', 'none');
});
});
</script>
</head>
<body>
<table>
<tr>
<td> <a href="#">Movie Part 1</a></td>
<td>01:23:26</td>
</tr>
<tr>
<td> <a href="#">Movie Part 1</a></td>
<td>01:23:26</td>
</tr>
</table>
</body>
From the above template, you can see that I am having 2 columns for this table and 1 columns has the tag with the href link and the other column doesnt have any tag.
Like I mentioned above, the script I am using to highlight the table row when clicked works. But I am trying to slightly modify the script so that it only execute the click effect only when the “a” tag inside the “tr td” is clicked. Right now, the table row is highlighted doesnt matter where I click inside the ‘tr’ area. It also highlights even if I click the second column inside the ‘tr’ which has no link.
How can I modify this above script so it highlights the entire table row ONLY when the ‘a’ tag inside the table row’s first column is clicked?
jQuery 1.7.x :
I’m thinking that you only need to change the background color of the
TRand not theTD. If I’m mistaken, just use this instead:jQuery 1.6.x and below :
EDIT
As per your comment below, you want to revert a row back to a normal background color when another row is clicked.
To do that efficiently, I’d suggest you resort to CSS rules. Heck, come to think of it, we should have done that even as the question was first answered.
First, define CSS rules like so:
then switch that using jQuery:
If just modifying the
trdoes not work for you, modify your CSS rules like so: