Highlighting Colour Of Row Upon Mouse Click
January 30th, 2008
I wanted some Javascript code that would allow me to highlight a row in a table, when the user clicked on a link or a radio button.
So, I tried out some code (below) to get the effect I wanted.
First, the required Javascript.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <script type="text/javascript"><!-- var lastSelectedRow; //Assuming that the background colour for all rows is white by default var defaultRowBgColor = 'white'; function highlightrow(rowId) { //Clearing the background color of the previously highlit rows if(lastSelectedRow!=null) document.getElementById(lastSelectedRow).bgColor = defaultRowBgColor; //Highlighting the row specified by 'rowId' //Here, we highlight with yellow document.getElementById(rowId).bgColor = 'yellow'; lastSelectedRow = rowId; } --></script> |
Next, the section of the HTML code for the table, whose rows I want to highlight when the link “Click Me” is clicked.
The first row has the ID “row1″, so, calling highlightrow(‘row1′) indicates to that function to highlight only that row and reset the background colour of any previously selected row to the default colour.
The HTML code for the other rows in this table would similar to as shown below
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | <table>
<tbody>
<tr id="row1">
<td>row 1 column 1</td>
<td>row 1 column 2</td>
<td><a href="" onclick="highlightrow('row1'); return false;">Click Me</a></td>
</tr>
<tr id="row2">
<td>row 2 column 1</td>
<td>row 2 column 2</td>
<td><a href="" onclick="highlightrow('row2'); return false;">Click Me</a></td>
</tr>
<tr id="row3">
<td>row 3 column 1</td>
<td>row 3 column 2</td>
<td><a href="" onclick="highlightrow('row3'); return false;">Click Me</a></td>
</tr>
</tbody>
</table> |
That’s all there is to it. Hope this helps someone out there.
Thanks a lot this worked and saved my time.