Category Archives: Java Script

All abou Java script

Common DOM methods in Java Script

Below is the lists of few common DOM methods that can be used on most elements in a document. As DOM gives us generic access to the element, their attributes, styles defined in a given document.

1. getElementById(object_id) : This method is used to access a object with its ID, The only thing we should keep in mind that before calling this method the target object should be created on the DOM  tree, Otherwise error will be thrown.

syntax: <div style=”background-color:black”></div>
document.getElementById(“myId”)

2 appendChild(node): Inserts the specified node or object at the end of the current container object. A frequently used method for dynamically appending a new element or text to the document.

3 insertBefore(newElement, targetElement): This inserts a node before the target node to the same Parent Node.

syntax : document.getElementById(“myId”).insertBefore(newCild, andTheOldTargetChild)

4 insertAfter(newElement, targetElement): This inserts a node after the target node to the same Parent Node.

syntax: document.getElementById(“myId”).insertBefore(newCild, andTheOldTargetChild)

5 removeChild(childreference) : This method is used to remove a child from a Given Parent Node.

syntax : document.getElementById(“myId”).removeChild(childId);

6 getAttribute(attributeName): Returns the value of the attribute named attribute of the current node.

document.getElementById(“myId”).getAttribute(“style=”)

7 getElementsByClassName: This method is very useful and widely used some of the known JS lib frameworks. This method return the reference of all the objects who has the same CSS class name assigned. It will return an array collection.

var arr[]=document.getElementById(“myId”).getElementsByClassName(“subMenus”)

8 getElementsByTagName(tagName): This method is having same nature of the above with only a difference that it sends the list of collection by TAG name.

var tags[]=document.getElementsByTagName(“a”) //returns all anchor tags list on page

9 hasAttribute(attributename): This method is used to verify the if a particular attribute has been defined for a given Node.

if (document.getElementById(“myId”).hasAttribute(“style”)){

//returns true;

}

10 setAttribute(attributename, value, [iecaseflag]): As the name said we can use this method to set attribute on a given node. and before assigning use the “hasAttributes” method.

Syntax: document.getElementById(“myId”).setAttribute(“valign”)=”center”

11 removeAttribute(attributename): As a name suggest this is used to remove a attribute.

syntax: document.getElementById(“myId”).removeAttribute(“style”);

12 innerHTML Property : The easiest way to get or modify the content of an element is by using the innerHTML property. innerHTML is not a part of the W3C DOM specification. However, it is supported by all major browsers. The innerHTML property is useful for returning or replacing the content of HTML elements (including <html> and <body>), it can also be used to view the source of a page that has been dynamically modified.

Hope This helps.


Thanks
R Vashi

Using eval() method in Java Script

The eval() method accepts a string of JavaScript statements(method, expressions)  and evaluates it as JavaScript source code.
eval() returns the value of the executed JavaScript statement.

WE mainly use eval() method while working with AJAX response which sometime contains some executable java script code to run.
Even many of the Java script lib/framework uses this heavily in their AJAX frameworks.

Syntax:
1. eval(statement) //statement can be any java script method.

2. eval(string) //any raw string containing the java script expressions. e.g eval(“alert(‘hello’)”);
First, eval() determines if the argument is a valid string, then eval() parses the string looking for JavaScript code. If it finds any JavaScript code, it will be executed the same way it execute the other methods defined in script tag.

[NOTE] This method is widely supported by most of the known browsers like IE, Mozilla, OPera, Safari, Chrome.

Hope this helps.


Thanks
R Vashi

Calling Browser Function for Fullscreen window using Java Script on IE

Hi All,

In this article I will show how to call browser function to full screen the window using Java Script+ActiveX. This example is based on IE. although it is very easy to use Window.open method in Java script to achieve the same but sometime we might face the need to use the same behavior which IE browser F11 gives.

function fullScreenWindow()
{
try{
// Get the ActiveX object from the Window
var acvxObj= new ActiveXObject("Wscript.shell");
// Now sends a key to fullscreen
acvxObj.SendKeys("{F11}");
}catch(e){

}
}

You can use the same function for any toggling full screen effect.

[NOTE] Whenever you call this method you will get a confirmation from IE Browser for ActiveX use.

Hope this helps.


Thanks
R Vashi.

Detecting Browsers using Java Script

Hi All,

Although it is not a rocket science to get the browser details using any technology script, but i will show a very Object oriented way to display the browser details using java script.

Step 1: Create one JS file, Name it CheckBrowser.js

Step 2: Write the below code in the file.

function IsBrowser(){
var agt=navigator.userAgent.toLowerCase();
this.major = parseInt(navigator.appVersion);
this.minor = parseFloat(navigator.appVersion);
this.nav  = ((agt.indexOf(‘mozilla’)!=-1) && ((agt.indexOf(‘spoofer’)==-1)  && (agt.indexOf(‘compatible’) == -1))); // FireFox/Mozilla

// add your browsers detection code here.
// e.g this.ie=

}

Step 3: Add the js in the Html/JSP/ASP/PHP file.
// <![CDATA[
javascript” >
// ]]>

Step 4: Invoke the function in Object oriented way

var is = new IsBrowser();
alert(is.nav);


Thanks
R Vashi

Closing browser window or tab in Mozilla/Firefox

Hi All,

Sometime we face the problem in closing a window/tab in Mozilla Firefox. The reason is that Firefox configuration doesn’t allows users to close active tabs or windows which are not opened by the script. The script means here refers to the pop up windows, opened using “window.open()” method.

Below I will share a very tricky steps to do that.

Steps:
–          Open Mozilla
–          Type “about:config” in address bar
–          You will see a list of some configurations
–          Search for “dom.allow_scripts_to_close_windows” and toggle to “true”, by default value will be “false”

Now create one HTML page, and add the below java script method to close the window.

<script>

function closeWin(){
window.close();
}

</script>


Thanks
R Vashi

Reading query parameters using Java Script

Hi,

One of the best mechanism passing data between pages is query strings in the URL. As we know server side scripts like JSP,SERVLETS,ASP,PHP supports very easy way to parse query paremeters,

But  Java script being a client side script also supports a very easy way to parse the query parameters in the URL.

Use the below method and see the how easy we achived.

<script>

var url = window.location.toString(); // read the URL
url.match(/\?(.+)$/);
var prms = RegExp.$1;

var prms = prms.split(“&”); //SPLIT THE VALUES IN ARRAY
var stringList = {};

for(var i=0;i<prms.length;i++){
var tmpKey = prms[i].split(“=”);
stringList[tmpKey[0]] = unescape(tmpKey[1]);
}

for(var j in stringList){
document.write(j+” = “+stringList[j]+”<br/>”);
}
</script>

Thanks

R Vashi

Pagination in Java Script(using prototype.js)

<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.0 Transitional//EN”>
<HTML>
<HEAD>
<TITLE> New Document </TITLE>

<script src=”prototype.js” type=”text/javascript”></script>
<SCRIPT LANGUAGE=”JavaScript”>
<!–
/*
Configurations for Paging

*/
var maxRecordShow=10;    // assgin from the config files
var totalRecordInDB=53; // get the record count from the backend, and assign here

var totalRecordCount=(totalRecordInDB/maxRecordShow);
var maxTotalPage=Math.ceil(totalRecordCount);

var currentPageSet=1;
var previousPageSet=0;

var nextPointer;
var prevPointer;

//–>
</SCRIPT>
</HEAD>

<BODY>
Page<div id=”pg” style=”display:inline”> 1</div> out of <span id=”total”></span> <br><br>
Records<br><div id=”rec” style=”display:inline”></div> <br><br>

<a href=”#?” id=”prev” onClick=”prevList()”>prev</a>&nbsp;&nbsp;   <a href=”#?” id=”next” onClick=”nextList()”>next</a>
<!– Data Table –>
<table id=”recTbl” name=”recTbl” cellspacing=”4″ cellpadding=”0″ border=”1″>
<tbody><tr>
<td>Title</td>
<td>Category</td>
<td>Type</td>
<td>Location</td>
</tr></TBODY>

</tbody>
</table>
<!– End Data Table –>

<a href=”#?” id=”prev” onClick=”prevList()”>prev</a>&nbsp;&nbsp;   <a href=”#?” id=”next” onClick=”nextList()”>next</a>
</BODY>

</HTML>

<SCRIPT LANGUAGE=”JavaScript”>

$(“total”).innerHTML=maxTotalPage;

function nextList(){
if(currentPageSet <maxTotalPage){
currentPageSet=currentPageSet+1;
nextPointer=maxRecordShow*currentPageSet;
prevPointer=nextPointer-(maxRecordShow-1);
previousPageSet=currentPageSet-1;
}
$(“pg”).innerHTML=currentPageSet;
$(“total”).innerHTML=maxTotalPage;
showNextPage(prevPointer,nextPointer);
}

function prevList(){
if(previousPageSet > 0 && previousPageSet<maxTotalPage){
previousPageSet=previousPageSet-1;
currentPageSet=previousPageSet+1;
nextPointer=maxRecordShow*currentPageSet;
prevPointer=nextPointer-(maxRecordShow-1);
}
showPrevPage(prevPointer,nextPointer);
$(“pg”).innerHTML=currentPageSet;
$(“total”).innerHTML=maxTotalPage;
}

function showNextPage(start,end){
//hide the current row set
if(start>maxRecordShow){
var st=start-1;
var en=st-(maxRecordShow-1);
for(i=st;i>=en;i–){
var id=”row”+i;
if($(id)){
$(id).style.display=”none”
}
}
}
//show the next row set
for(i=start;i<=end;i++){
var id=”row”+i;
if($(id)){
$(id).style.display=””
}
}
}

function showPrevPage(start,end){
//hide the current row set
for(i=start;i<=end+maxRecordShow;i++){
var id=”row”+i;
if($(id)){
$(id).style.display=”none”
}
}
//show the previous row set
for(i=end;i>=start;i–){
var id=”row”+i;
if($(id)){
$(id).style.display=””;
}
}
}

//@DummyMethod TO PUT RECORDS IN TABLE [in JSP just load the data from the server in the table dont use this method]
function putDummyRecords(){
var obj1=document.getElementById(“recTbl”);
var obj = obj1.getElementsByTagName(‘tbody’)[0];
for(i=1;i<=totalRecordInDB;i++){
var tr=document.createElement(“tr”);
var td1=document.createElement(“td”);
td1.appendChild(document.createTextNode(“Row”+i+””));
var td2=document.createElement(“td”);
td2.appendChild(document.createTextNode(” LLLLL “));
var td3=document.createElement(“td”);
td3.appendChild(document.createTextNode(” AAAAAA “));
var td4=document.createElement(“td”);
td4.appendChild(document.createTextNode(” ZZZZZZ “));
tr.appendChild(td1);
tr.appendChild(td2);
tr.appendChild(td3);
tr.appendChild(td4);
tr.setAttribute(“id”,”row”+i);
if(i > maxRecordShow){
tr.style.display=”none”;
}
obj.appendChild(tr);
}
}

// put dummy records in table
putDummyRecords();

// manage records on load
showNextPage(1,maxRecordShow);

</SCRIPT>

PS: Include proptype libs(effect.js, scriptaculous.js, prototype.js)