User login

Highlight Table Cells/Rows

A simple way to highlight table cells with JavaScript

Here is a simple script to highlight table cells on the MouseOver event. The script restores the original color
on the MouseOut event.



OneOne
TwoTwo
ThreeThree
FourFour


function hiLiteCells(){
var table = document.getElementById('myTable');
var x = table.getElementsByTagName('td');
for (var i=0;i<x.length;i++)
{
x[i].onmouseover = function (){
this.origColor=this.style.backgroundColor;
this.style.backgroundColor='#BCD4EC';
}
x[i].onmouseout = function () {
this.style.backgroundColor=this.origColor;
}
}
}

Here is what's happening in the function. First, we get a reference to the table element.

var table = document.getElementById('myTable');

Then we get a reference to all the cells in the particular table.

var x = table.getElementsByTagName('td');

Then we attach anonymous functions to the mouseover and mouseout events on the cells. The mouseover function stores
the cell's original color in a variable local to the cell object represented by the this keyword.

var x = document.getElementsByTagName('tr');

Don't forget to substitute your own table id for the myTable table id.

This script uses anonymous Javascript functions as explained in this article.

Highlight whole rows

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;}
}
}

This time we use a rows array to get access to table rows. The basic principle remains the same: the original background color
is saved in a custom property of a row object to be restored on the mouseout event.

Try it here:


OneOne
TwoTwo
ThreeThree
FourFour

Highlight whole rows 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.

Click on a row to change the color and click again to restore the original color:


OneOne
TwoTwo
ThreeThree
FourFour