Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

Friday, March 20, 2009

Object Oriented Programming (OOPs) in JavaScript

In this post basically I am trying to use Object Oriented Programming (OOPs) concept in JavaScript. Normally we tend to write just simple functions in JavaScript file, by this we are doing Procedural Programming. In this post I incorporated following OOPs concepts:
Object, Class, Inheritance, Encapsulation, Property, Polymorphism (Override).

Following is the sample code of JavaScript file (codes are self-explanatory with adequate comments):



//Class diagram --- Employee class inherits Person class and
// Person class itself contains Academic class.
//
// Person ---> Academic
// ^
// /|\
// |
// |
// Employee

//OOPS features ---
//Object, Class, Inheritance, Encapsulation, Property, Polymorphism (Override).

//==============================================================================//
//==============================================================================//

//Global functions, just like a Utility library.
//Function to display Academic's data.
Function.prototype.DisplayAcademic = function(paramAcademic)
{
alert("In DisplayAcademic -> " + "Degree :: " + paramAcademic.degree
+ ", Year :: " + paramAcademic.year + ", College :: "
+ paramAcademic.college + ", Percentage :: " + paramAcademic.percentage);
}

//Function to display Person's data.
Function.prototype.DisplayPerson = function(paramPerson)
{
alert("In DisplayPerson -> " + "Name :: " + paramPerson.name
+ ", Age :: " + paramPerson.age
+ ", Gender :: " + paramPerson.gender);

//Function call to display Academic's data.
Function.prototype.DisplayAcademic(paramPerson.GetAcademic());
}

//==============================================================================//
//==============================================================================//

//Person class definition.
function Person(paramName, paramAge, paramGender)
{
//Person class variable.
this.name = paramName;
this.age = paramAge;
this.gender = paramGender;

//Get/Set property of Person class.
var academic;
this.GetAcademic = function(){return academic;}
this.SetAcademic = function(paramAcademic){academic = paramAcademic;}

//Function to display Person's data.
this.display = function(objectEmployee)
{
Function.prototype.DisplayPerson(objectEmployee);
}
}

//Academic class definition.
function Academic(paramDegree, paramYear, paramCollege, paramPercentage)
{
//Academic class variables.
this.degree = paramDegree;
this.year = paramYear;
this.college = paramCollege;
this.percentage = paramPercentage;
}


//Employee class definition.
function Employee(paramCompany, paramExperience)
{
//Employee class variables.
this.company = paramCompany;
this.experience = paramExperience;

/*
//User inputs
var degree = prompt("Degree", "Please enter your degree.");
var year = prompt("Year", "Please enter your passing year.");
var college = prompt("College", "Please enter your college.");
var percentage = prompt("Percentage", "Please enter your percentage.");
*/
//Call to set the academic property in Person class.
//this.SetAcademic(new Academic(degree, year, college, percentage));

this.SetAcademic(new Academic("M.C.A", 2005, "D.D.U", 67.00));

//Function to display Employee class data.
this.displayEmployee = function()
{
alert("In Employee -> " + "Company :: " + this.company
+ ", Experience :: " + this.experience);
this.display(this);
}
//To override base class function, just keep the function name same.
//In above function, if we change the function name from 'displayEmployee'
//to 'display', then always child class function gets called.
}

//==============================================================================//
//==============================================================================//

//Page load function.
function load()
{
/*
//User inputs.
var name = prompt("Name", "Please enter your name.");
var age = prompt("Age", "Please enter your age.");
var gender = prompt("Gender", "Please enter your gender.");
var companyName = prompt("Company Name", "Please enter your company name.");
var experience = prompt("Experience", "Please enter your total experience.");
*/
//Create a Employee class instance.
//var avin = new Employee(companyName, experience, name, age, gender);

//Set the base (Person) class.
Employee.prototype = new Person("Avi", 28, "M");
var avin = new Employee("PSL", 4.00);

alert("Is Employee Object is instance of Employee class? "
+ (avin instanceof Employee)
+ "\nIs Employee Object is instance of Person class? "
+ (avin instanceof Person));

if(confirm("Do you want to display Employee data?"))
{
//Call to display Employee's data.
avin.displayEmployee();

//Direct base (Person) class function call.
avin.display(avin);
}
}




Following is the sample HTML file to test the above JavaScript file:



<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>OOPs in JavaScript</title>

<script src="OOPsInJavaScript.js" type="text/javascript"></script>

</head>
<body onload="javascript:load();">
OOPs in JavaScript sample.
</body>
</html>




Following image displays Employee's class object:



Following image displays Academic's class object:



Please feel free to write if I miss something or to improve the post.


References:
The JavaScript Object Model

Object Oriented Programming in JavaScript

Friday, January 16, 2009

Error handling in JavaScript

One way to handle error in JavaScript is to use simple try-catch block.



function foo(flag)
{
try
{
//Your code
}
catch(exception)
{
//Log exception in error log using exception object
}
}



In the above approach we have to write try-catch in all required functions.

Second approach is to register a function on window object which will get called always. It is similar to Page_Error function implementation in ASP.Net.



//Register handleError function to handles all browser error messages
window.onerror = handleError;

//Function to handle all errors.
function handleError(exception)
{
//Perform log operation
return true;
}



References :
JavaScript Error Handling

Error Handling

Error handling in javascript

Wednesday, October 1, 2008

JavaScripts Tips n Tricks

1) ClientID usage :

If you want to access the a Server side TextBox / Control written in ASP.Net from JavaScript code, then first you have get the clientID of that server control and then you can change access it.



<asp:TextBox ID="textBox1" Wrap="true" TextMode="MultiLine" runat="server" Width="215px"></asp:TextBox>

<script type="text/javascript">
var txtID = '<%= textBox1.ClientID %>';

document.getElementById(txtID).innerText = '';
</script>



Note: If an external JavaScript file is referenced in ASPX page, then ASP.NET won't be preprocessing it for server tags (<%...%>), as it isn't part of a ASPX file. You probably need to include the JavaScript code directly in the ASPX file (inline JavaScript code), or set up a global variable in there that is accessed by the JS file when it needs the clientID.



2) String to Number conversion :


var num = Number("11");




3) Case-Insensitive search :


//To make case-insensitive search, used SEARCH instead of INDEXOF.
var sampleString = 'Search case-insensitive based on InputString';
var index = sampleString.search(/InputString/i);




4) unescape() function :


//The unescape() function decodes a string encoded with escape().
var sURL = unescape(window.location.href);


Reference:
JavaScript unescape() Function



5) Trim string :


str = str.replace(/^\s*((?:[\S\s]*\S)?)\s*$/, '$1');




6) Encode string :


str = encodeURIComponent(str);




8) Date Validation :



function isValidDate(strNewDate)
{
var newDate = new Date(strNewDate);

if (newDate.toString() == "NaN" || newDate.toString() == "Invalid Date")
return false;
else
{
var currentDate = new Date();

//Check whether new date is greater than current date.
if( newDate.getTime() < currentDate.getTime() )
return false;
else
return true;
}
}





9) Number/Numeric Validation :



function isValidNumber(strInput)
{
var validChars = "0123456789.";
var isNumber=true;
var char;

for (i = 0; i < strInput.length && isNumber == true; i++)
{
char = strInput.charAt(i);
if (validChars.indexOf(char) == -1)
isNumber = false;
}

return isNumber;
}




Following code checks whether there are any number in a given string :


var regExp = /[0-9]+/g
var strNumber = new String("93932")

if(regExp.test(strNumber))
{
//There are numbers in strNumber.
}
else
{
//There are no numbers in strNumber.
}





10) String Validation :



function isValidString(strInput)
{
strInput = strInput.replace(/^\s*((?:[\S\s]*\S)?)\s*$/, '$1');

if(strInput == '')
return false;
else
return true;
}





11) Cancel an event :



function onClick()
{
window.event.returnValue = false;
return false;
}





12) Do postback or call server side function :


HTML code :


<asp:Button ID="btnUpdate" runat="server" Text="Update" OnClientClick="onUpdateClick();">



JavaScript code :


function onUpdateClick()
{
var evenArgs = "Server Call";
__doPostBack('<%= btnUpdate.ClientID %>',evenArgs);
}



CSharp (C#) code :


protected void Page_Load(object sender, EventArgs e)
{
string controlName = Request.Params.Get("__EVENTTARGET");
if (!string.IsNullOrEmpty(controlName))
{
if (controlName.Contains("btnUpdate"))
update();
}
}


void updateIssue()
{
string eventArgument = Request.Params.Get("__EVENTARGUMENT");
//do other operations
}





13) Get html element's top/left position :



function getPosition(elementID)
{
var obj = document.getElementById(elementID);
var top = obj.offsetTop;
var left = obj.offsetLeft;

while(obj.offsetParent != null)
{
obj = obj.offsetParent;
top += obj.offsetTop;
left += obj.offsetLeft;
}

alert("Top : " + top + " Left : " + left);
}





14) Types of dialog boxes in JavaScript :


alert


alert("Alert dialog box");



confirm


var response = confirm("Do you want to continue?");
if (response)
{
//true if OK is pressed
}
else
{
//false if Cancel is pressed
}



prompt


var response = prompt('Enter your name : ', 'Avi');
if (response) //Equivalent to --- if( (response != null) && (response != '') )
{
alert("You entered : " + response);
}
else
{
alert("You pressed Cancel or no value was entered.");
}


Reference :
Three Types of Dialog Boxes in JavaScript

Wednesday, August 20, 2008

Registering multiple functions to an event to an html object in JavaScript

The usual common way to register a function to an event to an html object in JavaScript is as follows:



//Registering mouse down event.
document.onmousedown = mouseDown;



The problem in above implementation is if you/someone also want to call some different function(s) on same event and for same html object, then only one function will gets called (probably the function which registered last to the event). So if you want to fire all registered functions of a particular event and of a particular html object, then you have to change your approach to event registration.
To register multiple functions for an event to an html object, you can use following approach:




//Function to add mulitple events to single object.
function AddEvent(obj, eventType, functionName)
{
if (obj.addEventListener)
{
obj.addEventListener(eventType, functionName, false);
return true;
}
else if (obj.attachEvent)
{
var r = obj.attachEvent("on"+eventType, functionName);
return r;
}
else
{
return false;
}
}


//Registering 3 different functions to same event and to same html object.
AddEvent(document, 'mousedown', mouseDownFirst);
AddEvent(document, 'mousedown', mouseDownSecond);
AddEvent(document, 'mousedown', mouseDownThird);


//Functions to test above registered functions.
function mouseDownFirst (){ alert('mouseDownFirst'); }
function mouseDownSecond(){ alert('mouseDownSecond'); }
function mouseDownThird (){ alert('mouseDownThird'); }




Similary to un-register functions we can write following code :


// Remove the specified function registeration for specified event handler on obj object.

//For IE
obj.removeEventListener(eventName, functionName);
//For Non-IE
obj.detachEvent("on"+eventName, functionName);



Note: Sometime to get the effect of updated JavaScript, browser cache deletion required.

Wednesday, July 23, 2008

Decode-Encode in JavaScript/C#

This article basically focused on doing the encoding of special characters in JavaScript and its Decoding in C#. If we go for default libraries/functions provided in JavaScript/C#, then it skips some special characters while doing the Encode/Decode.


Note: To see the complete list of libraries/functions for Encode/Decode in JavaScript/C#, please refer the links provided (at last of this post) for reference purpose.
Following are the list of special characters and its corresponding encoded characters:



var Character = new Array('%', ' ', '~', '!', '@', '#', '$', '^', '&', '*', '(', ')', '{', '}', '[', ']', '=', ':', '/', ',', ';', '?', '+', '\'', '"', '\\');


 
var URLEncoded = new Array('%25', '%20', '%7E', '%21', '%40', '%23', '%24', '%5E', '%26', '%2A', '%28', '%29', '%7B', '%7D', '%5B', '%5D', '%3D', '%3A', '%2F', '%2C', '%3B', '%3F', '%2B', '%27', '%22', '%5C');




Following are the code snippet for Encoding special characters in JavaScript:



//Variable that contains special characters.
var strSample;
//Trim the string varibale.
strSample = strSample.replace(/^\s*((?:[\S\s]*\S)?)\s*$/, '$1');
//Encode the string variable that contains special characters.
strSample = encodeURIComponent(strSample);
//Encode characters that are not covered in encodeURIComponent function.
var encodedCharacters = new Array('~', '!', '*', '(', ')', '\'');
var decodedCharacters = new Array('%7E', '%21', '%2A', '%28', '%29', '%60');
for(var i=0; i<encodedCharacters.length; i++)
{
strSample =
strSample.replace(encodedCharacters[i], decodedCharacters[i]);
}




Following are the code snippet for Decoding in C#:



//Following function Decode the encoded string,
//before that it replaces the “+” characters with “%2B”.
System.Web.HttpUtility.UrlDecode(strEncodedVariable.Replace("+", "%2B"));




Links for reference:
Comparing escape(), encodeURI(), and encodeURIComponent() --
http://xkr.us/articles/javascript/encode-compare/

INTRODUCTION TO URL ENCODING --
http://www.permadi.com/tutorial/urlEncoding/

The URLEncode and URLDecode Page --
http://www.albionresearch.com/misc/urlencode.php

MSDN HttpUtility.UrlEncode Method --
http://msdn2.microsoft.com/en-us/library/system.web.httputility.urlencode(vs.71).aspx

MSDN HttpUtility.UrlDecode Method (String) --
http://msdn2.microsoft.com/en-us/library/aa332862(VS.71).aspx

Encoding and Decoding URL strings --
http://www.kamath.com/codelibrary/cl006_url.asp

Tuesday, March 25, 2008

Display ToolTip in Javascripts

Following are the HTML and Javascripts code to display tooltip:

Html Code ---


<span id="spanName" style="font-weight: bold;" onmouseover="javascripts:DisplayToolTip('true');"
onmouseout="javascripts:DisplayToolTip('false');"></span>


<div id="divToolTip" style="position: absolute; display: none; z-index: 20;
background-color: #FFFFE1; border: solid 1px Black;">
</div>


<script type="text/javascript">
function DisplayToolTip(flag)
{
document.getElementById('divToolTip').style.left = window.event.x;
document.getElementById('divToolTip').style.top = window.event.y;

if(flag == 'true')
document.getElementById('divToolTip').style.display = 'block';
else if(flag == 'false')
document.getElementById('divToolTip').style.display = 'none';
}
</script>



Following image, shows how the ToolTip will appear after implementing the above code:








Thursday, March 13, 2008

JavaScript usage in Web Part


If you want to use JavaScript in your Web part then you have two options:


1) Refer to some external JavaScript file.



ClientScriptManager cs = Page.ClientScript;
// Include the required javascript file.
if (!cs.IsClientScriptIncludeRegistered("tab_javascript"))
cs.RegisterClientScriptInclude(this.GetType(), "tab_javascript",
"/_layouts/BCLBlast/tab.js");


I placed the JavaScript file at following location:


C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\LAYOUTS\BCLBlast







2) Write JavaScript in Web Part file.



// Initialize javascript variables to have list of all tabs and headers
if (!cs.IsClientScriptBlockRegistered("tabs_list"))
{
string tabVariables =
@"<script type=""text/javascript"">" +Environment.NewLine +
@"var tabs = [{0}] ;" + Environment.NewLine +
@"var tabheaders = [{1}] ;"+Environment.NewLine+
@"var _currentTab = null ;" + Environment.NewLine +
@"</script>";

string tabPages = "", tabHeaders = "";
for (int i = 0; i < SearchInformationSources.TotalSearchProviders; i++)
{
tabPages += "\"tab" + i.ToString() + "\", ";
tabHeaders += "\"tabheader" + i.ToString() + "\", ";
}

if (tabHeaders.Length > 1)
{
tabPages = tabPages.Remove(tabPages.Length - 2, 2);
tabHeaders = tabHeaders.Remove(tabHeaders.Length - 2, 2);
}

cs.RegisterClientScriptBlock(GetType(), "tabs_list",
String.Format(tabVariables, tabPages, tabHeaders));
}



Whole code snippet is as follows:





protected override void OnPreRender(EventArgs e)
{
ClientScriptManager cs = Page.ClientScript;
//Include the required javascript file.
if (!cs.IsClientScriptIncludeRegistered("tab_javascript"))
cs.RegisterClientScriptInclude(this.GetType(),
"tab_javascript", "/_layouts/BCLBlast/tab.js");


// Initialize javascript variables to have list of all tabs and headers
if (!cs.IsClientScriptBlockRegistered("tabs_list"))
{
string tabVariables =
@"<script type=""text/javascript"">" + Environment.NewLine +
@"var tabs = [{0}] ;" + Environment.NewLine +
@"var tabheaders = [{1}] ;" + Environment.NewLine +
@"var _currentTab = null ;" + Environment.NewLine +
@"</script>";

string tabPages = "", tabHeaders = "";
for (int i = 0; i < SearchInformationSources.TotalSearchProviders; i++)
{
tabPages += "\"tab" + i.ToString() + "\", ";
tabHeaders += "\"tabheader" + i.ToString() + "\", ";
}

if (tabHeaders.Length > 1)
{
tabPages = tabPages.Remove(tabPages.Length - 2, 2);
tabHeaders = tabHeaders.Remove(tabHeaders.Length - 2, 2);
}

cs.RegisterClientScriptBlock(GetType(), "tabs_list",
String.Format(tabVariables, tabPages, tabHeaders));
}
}




Here you to have to implement the OnPreRender method to write the JavaScript code.

Sunday, May 27, 2007

Ways of using Web service from JavaScript


1. Client side <--> ASPX page <--> Web service.
2. Client side <--> HTC file <--> Web service.
3. Client side <--> AJAX <--> Web service.
4. Client side <--> SOAP Request/Response <--> Web service.


1. Create a dummy aspx page that is used by JavaScript to use Web Service functions. JavaScript class calls aspx page and in turn aspx page calls Web Service. Here aspx page use Web Service by adding a Web Reference in project and create a object of Web Service class and process it as normal function calling.


2. HTC Usage –


HTML Page ----



<body>
<div id="service" style="behavior: url(webservice.htc)">

-------------
-------------

</body>





Java Script File ----



function asyncWSCall(strMethodName, strCountryName, boolAsync)
{
strMethodName == "getCurrentPositionData" ; //WebService function name

// Establish the friendly name "WS" for the WebServiceURL
//service.useService("http://localhost/DemoApp/SampleWebService.asmx?WSDL","WS");

// The following uses a callback handler named " processgetCurrentPositionData"
iCallID = service.WS.callService(processgetCurrentPositionData,
strMethodName, strCountryName, boolAsync);
}


function processgetCurrentPositionData(result)
{
-------
-------

document.getElementById('txtAr').value = result.value.xml;
}




Web Service ----


[WebMethod]
public XmlDocument getCurrentPositionData(string countryName, bool boolAsync)
{
------
------
}




3. AJAX Usage –

HTML Page ----


<body>
<form id="form1" runat="server">
<asp:ScriptManager runat="server" ID="scriptManagerId">
<services>
<asp:ServiceReference Path="WSForAJAX.asmx" />
</services>
</asp:ScriptManager>

-----
-----

</body>




Java Script File ----



function wsCallForCurrentPostion()
{
WSForAJAX.getCurrentPositionData(OnSucceededWithContext, OnFailed,"XmlDocument");
}



// This is the callback function invoked if the Web service succeeded.
// It accepts the result object, the user context, and the calling method name as parameters.
function OnSucceededWithContext(result, userContext, methodName)
{
var RsltElem = document.getElementById('txtAr').value;

var readResult;
if (userContext == "XmlDocument")
{
if (document.all)
readResult = result.documentElement.firstChild.text;
else // Firefox
readResult = result.documentElement.firstChild.textContent;

RsltElem.innerHTML = "XmlDocument content: " + readResult;
}
}



// This is the callback function invoked if the Web service failed.
// It accepts the error object as a parameter.
function OnFailed(error)
{
// Display the error.
var RsltElem = document.getElementById("ResultId");
RsltElem.innerHTML = "Service Error: " + error.get_message();
}




Web Service ----



[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Xml)]
public XmlDocument getCurrentPositionData(string countryName, bool boolAsync)
{
----
----
}




4. SOAP Usage –


Java Script File ----



//Function to create parameter for WebService method.
function createWSParam()
{
var strMethodName = 'getCurrentPositionData' ;
var strSoapContent = '<countryName>' + count4WSCall + '</ countryName >\n'
+ '<boolAsync>' + strCountryName + '</ boolAsync >\n' ;
}





//Function to create SOAP data packet.
function createSOAPData(strMethodName, strSoapContent)
{
var soapAction = 'http://tempuri.org/' + strMethodName ;
var url = 'http://localhost/DemoApp/SampleWebService.asmx' ;
var data = '<?xml version=\'1.0\' encoding=\'utf-8\'?>\n'
+'<soap:Envelope xmlns:xsi=\'http://www.w3.org/2001/XMLSchema-
instance\' xmlns:xsd=\'http://www.w3.org/2001/XMLSchema\'
xmlns:soap=\'http://schemas.xmlsoap.org/soap/envelope/\'>\n'
+ '<soap:Body>\n'
+ '<' + strMethodName + ' xmlns=\'http://tempuri.org/\'>\n'
+ strSoapContent
+ '</' + strMethodName + '>\n'
+ '</soap:Body>\n'
+'</soap:Envelope>' ;
}





//Function to create XMLHttpRequest.
function getXmlHttpObject()
{
var xmlhttp ;
if(window.ActiveXObject)
{
try
{
xmlhttp = new ActiveXObject('Msxml2.XMLHTTP');
}
catch (ex)
{
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
}
else if (window.XMLHttpRequest) //For Non-IE
{
xmlhttp = new XMLHttpRequest();
}
}





//Function to send the SOAP Request.
function sendSOAPDataToWebService(xmlhttp, url, data, soapAction)
{
xmlhttp.open('POST', url, true);
xmlhttp.onreadystatechange = processgetSOAPResponseData ;
xmlhttp.setRequestHeader('Content-Type', 'text/xml');
xmlhttp.setRequestHeader('SOAPAction', soapAction);
xmlhttp.send(data);
}





//Function to process the SOAP Response.
function processgetSOAPResponseData()
{
if (xmlhttp.readyState == 4)
{
if (xmlhttp.status == 200) // only if "OK"
{
try
{
if (window.ActiveXObject) // code for IE
{
doc = new ActiveXObject("Microsoft.XMLDOM");

doc.async="false";
doc.loadXML(xmlhttp.responseText);
}
else // code for Mozilla, Firefox, Opera, etc.
{
var parser=new DOMParser();
doc = parser.parseFromString(xmlhttp.responseText,"text/xml");
}

var rootNode = doc.documentElement;
// documentElement always represents the root node

if( rootNode.childNodes[0].childNodes[0].childNodes[0].nodeName
== "getCurrentPositionDataResult" )
{
//Method to process the SOAP data
getCurrentPositionData(rootNode) ;
}
}
catch (ex)
{
}
}
}
}



Web Service ----



[WebMethod]
public XmlDocument getCurrentPositionData(string countryName, bool boolAsync)
{
------
------
}








Suggested Links:

AJAX Example
http://ajax.asp.net/docs/ViewSample.aspx?sref=Sys.Net.SimpleWebService/cs/SimpleWebService.asmx

Use of Xml in AJAX
http://ajax.asp.net/docs/tutorials/CreateSimpleAJAXApplication.aspx
http://ajax.asp.net/docs/ViewSample.aspx?sref=EnhancingJavaScript/cs/Inheritance.aspx

HTC -
http://msdn.microsoft.com/archive/default.asp?url=/archive/en-us/samples/internet/behaviors/library/webservice/default.asp

HTC Example -
http://msdn2.microsoft.com/en-us/library/ms531033.aspx

HTC Result Object example --
http://msdn2.microsoft.com/en-us/library/ms531058.aspx

Debugging of Javascript

1) In IE –
Simply use external .js file


<script language="javascript" src="JavaScripts/WSCallViaHTC.js" type="text/javascript"></script>



2) In Mozilla –

a) FireBug enables you to step through client script and examine HTML DOM elements.
It also provides a script console, a command line, and other tools.




b) The JavaScript Debugger (also known as "Venkman") provides a JavaScript
debugging environment that includes a source-code browser and other features.




c) Web Developer Extension enables you to inspect the DOM and CSS styles.
 
Suggested Link:
Debugging Javascripts --
http://ajax.asp.net/docs/overview/92684ea0-7bb4-4a34-9203-3aa6394ce375.aspx

Issues related to multiple browser compatibility

Following are the issuses that i faced while developing a multiple browser compatible application:

1. Web service call should be SOAP Request/Response.



var strMethodName = 'getCurrentPositionData' ;
var strSoapContent =
'<counter4RouteID>' + count4WSCall + '</counter4RouteID>\n'
+ '<countryName>' + strCountryName + '</countryName>\n' ;



var soapAction = 'http://tempuri.org/' + strMethodName ;
var url = 'http://localhost/VEVistaMashUp/VEVistaMashUpService.asmx' ;
var data = '<?xml version=\'1.0\' encoding=\'utf-8\'?>\n'
+'<soap:Envelope xmlns:xsi=\'http://www.w3.org/2001/XMLSchema-instance\'
xmlns:xsd=\'http://www.w3.org/2001/XMLSchema\'
xmlns:soap=\'http://schemas.xmlsoap.org/soap/envelope/\'>\n'
+ '<soap:Body>\n'
+ '<' + strMethodName + ' xmlns=\'http://tempuri.org/\'>\n'
+ strSoapContent
+ '</' + strMethodName + '>\n'
+ '</soap:Body>\n'
+'</soap:Envelope>' ;





2. To use SOAP Request/Response we have to create the xmlHttp object. In IE we use ActiveXObject while in Non-IE we use XMLHttpRequest ().



var xmlhttp ;
if(window.ActiveXObject)
{
try
{
xmlhttp = new ActiveXObject('Msxml2.XMLHTTP');
}
catch (ex)
{
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
}
else if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}





3. SOAP request should be Asynchronous in case of Mozilla while IE support both Synchronous and Asynchronous web service call.



xmlhttp.open('POST', url, true);
xmlhttp.onreadystatechange = processgetCurrentPositionData ;
xmlhttp.setRequestHeader('Content-Type', 'text/xml');
xmlhttp.setRequestHeader('SOAPAction', soapAction);
xmlhttp.send(data);





4. IE support both xmlHttpObject.responseXml and xmlHttpObject.responseText while Mozilla supports only xmlHttpObject.responseText.


xmlhttp .responseText




5. For using xmlDocument in JavaScript we have use Microsoft.xmlDom in IE and DomParser in case of Non-IE browser.



if (xmlhttp4CurrentPos.readyState == 4)
{
if (xmlhttp4CurrentPos.status == 200) // only if "OK"
{
try
{
if (window.ActiveXObject) // code for IE
{
doc = new ActiveXObject("Microsoft.XMLDOM");

doc.async="false";
doc.loadXML(xmlhttp4CurrentPos.responseText);
}
else // code for Mozilla, Firefox, Opera, etc.
{
var parser=new DOMParser();
doc = parser.parseFromString(xmlhttp4CurrentPos.responseText,"text/xml");
}

var rootNode = doc.documentElement; // documentElement always represents the root node

if( rootNode.childNodes[0].childNodes[0].childNodes[0].nodeName == "getCurrentPositionDataResult" )
{
getCurrentPositionData(rootNode) ;
}
}
catch (ex)
{
}
}
}




6. Mozilla require ‘px’ to every points while IE assume unit without any ‘px’ or ‘%’ as ‘px’.



objMenu.style.left = vLeft + 'px';
objMenu.style.top = vTop + 'px';




7. In IE ‘event ‘ is a global variable that always refer to the current event while in Mozilla you have to explicitly specified the event with method.



onmouseover="displayInfo(event);"

function displayInfo(evt)
{
......
......
var e = (window.event) ? window.event : evt;
......
......
}




8. Mozilla don’t support document.all [‘tagID’], while document.getElementById (‘tagID’) is supported by every browser.


document.getElementById("flashObj")


9. Require to set the z-index in case of Opera to see the some object over another object.


z-index: 2


10. To insert some html as string during runtime requires '<div> …</div>’ tags in Non-IE while its work fine in IE. Also IE require some width of control. In case of button – it has some default height width but if your page consists of only DIV tag then we have to specify some height and width to it.



var strMediaPlayerContent = "<div>" ;

......
......

var objMediaPlayer = document.getElementById('div4MediaPlayer') ;
objMediaPlayer.innerHTML = strMediaPlayerContent + "</div>" ;


11. We have to create graphic object in case of Non-IE when we are using Virtual Earth APIs.


map = new VEMap( "USMap" );

if( typeof( window.innerWidth ) == 'number' ) //Non IE
Msn.Drawing.Graphic.CreateGraphic=function(f,b) { return new Msn.Drawing.SVGGraphic(f,b) }

map.LoadMap(new VELatLong(lat4USAirCraft, long4USAirCraft), 10 ,'h' ,true);

map.HideDashboard();


12. In JavaScript Debugger of Mozilla – after code execution cursor move to catch line (even if the code is correct).

13. In Mozilla use ‘\\’ instead of ‘/’ to specify file Path while using Query string.



"Videos\\Sample.MPG";


14. JavaScript debuggers in case of Mozilla are – Fire Bug, JavaScript Debugger and Error Console.


Google