Tuesday, August 28, 2007

Java Script For IE and FireFox

Currently many browsers are available in the market that is making life hell for programmers.

If syntax A is supported by Browser A then this syntax is not supported by Browser B.

The one very interesting I encountered when I was working on one of my project that is how java script supported by browsers.

There is a slight difference how the HTML tags are rendered by IE and FireFox.

Look at this scenario

<Child>Contnet of Child</Child>

This is interpreted in different ways by FireFox and IE.

How IE interprets

IE considers <parent>has a single child node called <child>

How FireFox interprets

On every new line, FireFox inserts empty text node. In the above case FireFox considers there are 3 child nodes.

This is how these tags will be rendered in FireFox

<Empty Text node 1>
<Child>Contnet of Child</Child>
<Empty Text node 2>

So, you see, first Child is the for IE, but an Empty text Node for FireFox.

The solutions may be:-

1. Put Everything in a single line:- <parent> <Child>Contnet of Child</Child> </parent>

But it is very impractical solution.

2. Change the ways you access the nodes.

First of all determine the browser used by the user.

function checkBrowser()
var browser=navigator.appName;
if (browser == "Microsoft Internet Explorer" )
return 0;
else if (browser == "Netscape")
return 1;

Once the browser is determined then return respectively value of the index variable from the function.

Now this index variable will be used to access the control in Java Script.

function checkValue()
var index;
var rowNo = 1;
index = checkBrowser();
var o = document.getElementById('<%=dgSystemList.ClientID%>');
var chk1= o.rows[rowNo].cells[0].childNodes[index];

Note:-This function is just for sample.

One thing to notice there are two ways to access child nodes.

1. children
2. childNodes

The Problem with the first method is that it is not compatible with firefox. It is working fine for IE.

Second method works fine for both the browsers.

To make your code compatible with both the browsers use childNodes method.
Hope this helps…

No comments:

back to top