Monday, May 2, 2011

Highlight HTML Table Rows with JavaScript

Highlight Table Rows on Mouseover


To highlight whole rows, use the following function:

function hiLiteRows(){
 var table = document.getElementById('myTable2');
 for (var i=0;i < table.rows.length;i++)
 {
  table.rows[i].onmouseover = function () {
   this.origColor=this.style.backgroundColor;
   this.style.backgroundColor='#BCD4EC';
  }
  table.rows[i].onmouseout = function () {this.style.backgroundColor=this.origColor;}
 }
}
We use a rows array to get access to table rows. The basic principle is as follows: the original background color is saved in a custom property of a row object to be restored on the mouseout event. The this keyword here refers to the row object.

-->

Highlight TableRows on Click Event


To highlight table rows on the click event, we modify the previous function:

function hiLiteRowsClick(){
 var table = document.getElementById('myTable3');
 for (var i=0;i < table.rows.length;i++){
  table.rows[i].onclick= function () {
   if(!this.hilite){
    this.origColor=this.style.backgroundColor;
    this.style.backgroundColor='#BCD4EC';
    this.hilite = true;
   }
   else{
    this.style.backgroundColor=this.origColor;
    this.hilite = false;
   }
    }
 }
}

Instead of the mouseover event, we use the onclick event to call the anonymous function.
The function will change the background color when a row is clicked for the first time. When a row is clicked again, the original color is restored. To keep track of the click sequence the function uses a custom property called hilite.
This property is set to true on the first click and set to false on the second one.

Related posts:

Hide columns in a table

Expand/collapse rows dynamically


No comments:

Post a Comment