Hover Table Row with Javascript
Back to home page | View Javascript file | Comment on this codeThis page uses a few easy javascript functions to assist in user-friendly and aesthetically-pleasing "row-selecting." You can now select an "option" from a table and this code provides a CSS-based visual color-change for that row (via a change of class).
This effect is accomplished via the onMouseOver for the HOVER effect and an onClick event for the "selecting" effect when you click/select the row of the table. The radio box will select to correspond with your choice.See the below example and subsequent code.
I am using the following style classes to implement this effect:
<style>
TR.class_hover{
text-align: center;
font-size: 12px;
font-weight:bold;
vertical-align: middle;
background-color: #B1CFF5;
cursor: pointer; /* hand-shaped cursor */
cursor: hand; /* for IE 5.x */
}
TR.class_no_hover{
font-size: 12px;
font-weight:bold;
vertical-align: middle;
/* background-color: #D0E4F8; */
text-align: center;
}
</style>
Then you simply give an id to each table-row element (TR) and use the following event-handlers to cause the desired effect.
<tr id='tr_1' onClick='selectRadio(1);'
onMouseOver="hover(this);"
onMouseOut="unHover(this, 1);"
Below are the javascript functions allowing this functionality for the row.
<script> var tr_selected = ''; function selectRadio(row_num){ unSelectAll(); if (document.Form.row_radio.length != undefined){ document.Form.row_radio[row_num - 1].checked = true; } else{ document.Form.row_radio.checked = true; } if (tr_selected != '') document.getElementById('tr_' + tr_selected).className = 'class_no_hover'; document.getElementById('tr_' + row_num).className = 'class_hover'; tr_selected = row_num; } function unSelectAll(){ if (document.Form.row_radio.length != undefined){ for (var i=0; i < document.Form.row_radio.length; i++){ document.Form.row_radio[i].checked = false; } } } function hover(obj){ obj.className='class_hover'; } function unHover(obj, row_num){ if (tr_selected != row_num) obj.className = 'class_no_hover'; } </script>
Back to home page | View Javascript file | Download the full example