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


A Simple Way to Highlight Table Cells 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.

Friday, December 10, 2010

Insert Backslash Before a Double Quote

Sometimes, you need to dynamically write html text from JavaScript. If the text contains a combination of single and double quotes, you may run into problems. Here is a simple function to avoid those problems.
function insertBackslashBeforeDoubleQuote(str){
 var reg = /"/g;
 var newstr = '\\"';
 return str.replace(reg,newstr);
}
As you see, the function uses a RegExp object on the first line to look for a double quote:
reg = /"/g;
 
The second line defines our replacement string - \"
The backslash in front of the quote has to be escaped with another backslash.
newstr = '\\"';
The last line searches the string and if a double quote is found it is replaced by our newstr pattern.
return str.replace(reg,newstr);
Here is a similar function that inserts a backslash before a single quote if it is contained in the string argument.
function insertBackslashBeforeSingleQuote(str){
 var reg = /'/g;
 var newstr = "\\'"
 return str.replace(reg,newstr);
}


Some other posts:

A JavaScript endsWith function

Highlight HTML Table Rows with JavaScript

Wednesday, November 17, 2010

"Event is Not Defined" Error in Firefox

This error may occur when you try to attach a JavaScript function dynamically to page elements and pass an event to the function. An example:
var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; i++) {
    if (inputs[i].type == 'text') {
        inputs[i].onkeypress = function() { return isNumericKey(event); }
    }
};

Here is a listing of the validation function:


/* Numeric Validation */
function isNumericKey(evt) {
    var charCode = (evt.which) ? evt.which : event.keyCode;
    if (charCode >= 48 && charCode <= 57 || charCode == 46) {
        return true;
    }
    else {
        return false;
    }
}
 
This code will work perfectly in IE and it won't allow users to type any other characters than numeric. However, in Firefox, it will throw an error: "event is not defined".

First solution:

Check whether the event is defined in Firefox and attach a reference to the validation function.

if (typeof (event) == "undefined")
    inputs[i].onkeypress = isNegativeNumericKey;
else
    inputs[i].onkeypress = function() { return isNumericKey(event);}

In this case, the event is a global variable that does not exist in Firefox. We could have rewritten the type check as follows:

if (typeof (window.event) == "undefined") ...

Second solution:

Use the following version of the function call in Firefox by passing the event parameter to the function that handles the keypress event:

inputs[i].onkeypress = function(event) { return isNumericKey(event);}

But this would not work in IE.  The solution: normalize the Event interface in the function body:

function(event) { 
   event = event || window.event;
   return isNumericKey(event); 
}

Wednesday, December 9, 2009

A Graph in Table Without Image

Here is a simple script to add a graph to a table cell.





Each table row consists of 2 cells. The first cell contains a numeric value. For each row, in the second cell, the script creates a span with a width equal to the value in the first cell:


It assumes you set a style for a "graph" class. Alternatively, you could set background color in the script. Also, the maximum span width of 100 is assumed.

A side note: to create a rounded span in Firefox, use the following style for the "graph" class:
-moz-border-radius: 10px;
var tbl = document.getElementById('tbl');
for(var i=0; i<tbl.rows.length; i++){
var val = tbl.rows[i].cells[0].innerHTML;
var span = document.createElement("span");
span.style.width = val/100*100;
span.className = "graph";
var cell =tbl.rows[i].cells[1];
cell.style.textAlign= 'left';
cell.appendChild(span);
}

Wednesday, May 20, 2009

Enumerate Array or Object

This is how you could enumerate properties of a JavaScript array:

var arr = ['a', 'b', 'c'];

for (var prop in arr)
alert (prop + ":"+ arr[prop]);

Result:
0:a
1:b
2:c

Thursday, March 26, 2009

Expand/Collapse Rows Dynamically with DOM and JavaScript

Suppose, you have a table structured as follows:



The first line for a new month is always a total of the project amounts. This structure comes from an sql query, using the Oracle GROUP BY CUBE clause. Would not it be nice to be able to see only the rows with intermediate totals, expanding this or that month if necessary.



Here is a set of JavaScript functions that collapses and expands table rows:

var tbl;

function getParent(el, pTagName) {
if (el == null) return null;
else if (el.nodeType == 1 && el.tagName.toLowerCase() == pTagName.toLowerCase())
return el;
else
return getParent(el.parentNode, pTagName);
}


function toggleSection(lnk){

var td = lnk.parentNode;
var table = getParent(td,'TABLE');
var len = table.rows.length;
var tr = getParent(td, 'tr');
var rowIndex = tr.rowIndex;
var rowHead=table.rows[rowIndex].cells[1].innerHTML;

lnk.innerHTML =(lnk.innerHTML == "+")?"-":"+";
vStyle =(tbl.rows[rowIndex+1].style.display=='none')?'':'none';

for(var i = rowIndex+1; i < len;i++){
if (table.rows[i].cells[1].innerHTML==rowHead){
table.rows[i].style.display= vStyle;
table.rows[i].cells[1].style.visibility="hidden";
}
}
}

function collapseRows(){
tables =document.getElementsByTagName("table");
for(i =0; i < tables.length;i++){
if(tables[i].className.indexOf("expandable") != -1)
 tbl =tables[i];
}

if(typeof tbl=='undefined'){
 alert("Could not find a table of expandable class");
 return;
}

//assume the first row is headings and the first column is empty
var len = tbl.rows.length;
var link = '<a href="#" onclick="toggleSection(this);return false;">+ </a> ';

var rowHead = tbl.rows[1].cells[1].innerHTML;

for (j=1; j < len;j++){
 //check the value in each row of column 2
 var m = tbl.rows[j].cells[1].innerHTML;

 if(m!=rowHead || j==1){
  rowHead=m;
  tbl.rows[j].cells[0].innerHTML = link;
  tbl.rows[j].style.background = "#CCFF99";
 } 
 else
  tbl.rows[j].style.display = "none";
}
}

window.onload=collapseRows;

Let me briefly explain what the script does. When a page has loaded, the collapseRows function is called. It looks for a table with a class named 'expandable'. If such a table is found, a reference to the table is stored in a variable tbl, and the number of rows in the table is stored in a variable len.

var len = tbl.rows.length;

Then, we create a variable that holds an html link that will call the toggleSection function when linked. The function parameter will contain a reference to the link itself. We using the this keyword here.
var link = '<a href="#" onclick="toggleSection(this);return false;">+ </a> ';

The variable rowHead in the next statement will contain the text in the second column of the first row(not counting the table head). In this table it is January.

var rowHead = tbl.rows[1].cells[1].innerHTML;

The next piece of the code loops through each row, and if the text in the second column contains repeating information, it hides that row. Also, it assigns a different color to the first row with non-duplicate text.
for (j=1; j < len;j++){
 var m = tbl.rows[j].cells[1].innerHTML;
 if(m!=rowHead || j==1){
  rowHead=m;
  tbl.rows[j].cells[0].innerHTML = link;
  tbl.rows[j].style.background = "#CCFF99";
 }
 else
  tbl.rows[j].style.display = "none";
}

The next function, toggleSection, hides or collapses rows with duplicate months. As a parameter, the function accepts a reference to the link that calls the function. Using the link reference, we get a reference to the containing table cell, row, and then the row index for the cell:

var td = lnk.parentNode;
var tr = getParent(td, 'tr');
var rowIndex = tr.rowIndex;

We obtain text in the second column of that row (January or February, in this example):

var rowHead=table.rows[rowIndex].cells[1].innerHTML;

Next, we switch the text of the link from plus to minus or vice versa.

lnk.innerHTML =(lnk.innerHTML == "+")?"-":"+";

Then, we prepare a style to be used for the next rows.

vStyle =(tbl.rows[rowIndex+1].style.display=='none')?'':'none';

Then, we loop through the table, and if the text in the second column of each row is the same as the text in the same column of the row that contains the link, we hide or show that row depending on its initial state.

for(var i = rowIndex+1; i < len;i++){
if (table.rows[i].cells[1].innerHTML==rowHead){
 table.rows[i].style.display= vStyle;
}

We also hide the repeating text in the second column:

table.rows[i].cells[1].style.visibility="hidden";

Don't forget, the table must contain an empty first column to hold a plus or minus sign and have a class named 'expandable'.

See a demo here.

The script can be downloaded here.

Another post dealing with the HTML table :
Highlight Table Cells with JavaScript