You are on page 1of 32

Javascript: Window

The name of the child window is "myChild". Any values in the child window are referenced using the name of the parent window. The parent has total control of its immediate child window and any subsequent child (grandchild) windows. If the parent window is destroyed, all control for the remaining child windows is lost. A child window can find out who its parent is by using the opener method. You use the opener method as shown in the following: var name = window.opener.document.name; This will return the name of the parent document to the name variable. You can use multiple instances of opener if you have several levels of windows. If a grandchild wanted to reference its grandparent, it could do so by simply adding another level. window.opener.opener.document.form1.textbox.value For a window to refer to its own properties, you can use the window self property. Suppose you wanted to set a textbox value within a form document in a window. self.document.formName.textbox.value = "JavaScript is cool";

Creating Windows
The open method can be used to create any primary or secondary window. window.open("web.html", "newWin", "resizeable,menubar,toolbar"); This creates a window that is resizable, contains a menu bar, and has a toolbar. The "web.html" is the file that will open in the newly created window. "newWin" represents the name of the window object. Other features include outerHeight, outerWidth, innerHeight, innerWidth, alwaysRaised, alwaysLowered, location, screenY, and screenX. The features are specified in the parameters of the open function. <HTML> <HEAD> <TITLE> Window Example - Parent</TITLE> <SCRIPT LANGUAGE="Javascript"> <!-function openWin(){ childWin=open("child.htm", "ChildWin", "toolbar,scrollbars,menubar,status,innerwidth=250,innerheight=350"); } function sendToChild(){ childWin.document.childForm.childText.value = document.parentForm.parenttext.value; } // End Hide--> </SCRIPT> </HEAD> <BODY> <P> <CENTER> <B>Window Example - Parent Window</B> <BR><BR><BR> </CENTER> <FORM NAME="parentForm"> Click on the Button below to open a Child window: <BR><BR> <INPUT TYPE="button" NAME="submit" VALUE="Open Child Window" onclick="openWin()"> <BR><BR><BR> <TABLE> <TR><TD ALIGN=left> <INPUT TYPE="text" NAME="parenttext" size=45></TD> <TD ALIGN=left> <INPUT TYPE="button" NAME="submit" VALUE="Send To Child" onclick="sendToChild()"> </TD> </TR> <TR><TD ALIGN=left> <INPUT TYPE="text" NAME="received" size=45></TD> <TD ALIGN=left> This text comes from the child.

</TD> </TR> </TABLE> </FORM> <BR><BR><BR> </BODY> </HTML>

Child Window Code for Window Example


File:child.htm <HEAD> <TITLE> Window Example - Child</TITLE> <SCRIPT LANGUAGE="Javascript"> <!-function sendToParent(){ window.opener.document.parentForm.received.value = document.childForm.sendText.value; } --> </SCRIPT> </HEAD> <BODY> <P> <CENTER> <B>Window Example - Child window</B> <BR><BR><BR> </CENTER> <FORM NAME="childForm"> <TABLE> <TR><TD ALIGN=left> <INPUT TYPE="text" NAME="sendText" size=45></TD> <TD ALIGN=left> <INPUT TYPE="button" NAME="submit" VALUE="Send Text" onclick="sendToParent()"> </TD> </TR> <BR> <TR><TD ALIGN=left> <INPUT TYPE="text" NAME="childText" size=45> </TD> <TD ALIGN=left> Text Received from Parent: </TD> </TR> </TABLE> </FORM> <BR><BR><BR> </BODY>

Window Object Properties Array:


<HTML><HEAD> <TITLE>Window Object Properties Array</TITLE> </HEAD><BODY><SCRIPT> for (var i in window) { document.write ("Window property(" + i + "): " + window[i] + "<BR>"); } </SCRIPT></BODY></HTML> screen

The screen object provides an access to various properties of the user's screen. These properties are often accessed and used sizing windows that various scripts open. Properties of the screen Object Item Description AvailHeight Returns the pixel height of the user's screen, minus the toolbar or any other "permanent" objects. availWidth Returns the pixel width of the user's screen, minus the toolbar or any other "permanent" objects. colorDepth Returns the maximum number of colors the user's screen can display. This is in bit format. height Returns the pixel height of the user's screen. pixelDepth Returns the number of bits per pixel of the user's screen. Internet Explorer did not support this property at the time of this writing and returns undefined. width Returns the pixel width of the user's screen.

<html><head> <script language="JavaScript1.2"> <!-function openWin(){ var myWin = open("", "","width=450,height=200"); myWin.document.write("The myWin.document.write("The myWin.document.write("The myWin.document.write("The myWin.document.write("The myWin.document.write("The myWin.document.close(); availHeight is: " + screen.availHeight + "<br>"); availWidth is: " + screen.availWidth + "<br>"); colorDepth is: " + screen.colorDepth + "<br>"); height is: " + screen.height + "<br>"); pixelDepth is: " + screen.pixelDepth + "<br>"); width is: " + screen.width + "<br>");

} --> </script></head><body><form name="myForm"> <input type=BUTTON value="Click to See Screen Properties" name="myButton" onClick="openWin()"> </form></body></html>

screen.availLeft <html><head><title>History</title> </head><body><script type="text/javascript"> document.writeln("screen.availTop: " + screen.availTop + "<br />"); document.writeln("screen.availLeft: " + screen.availLeft + "<br />"); document.writeln("screen.availWidth: " + screen.availWidth + "<br />"); document.writeln("screen.availHeight: " + screen.availHeight + "<br />"); document.writeln("screen.colorDepth: " + screen.colorDepth + "<br />"); document.writeln("screen.pixelDepth: " + screen.pixelDepth + "<br />"); </script></body></html>

screen.availTop
<html><head><title>History</title> </head><body><script type="text/javascript"> document.writeln("screen.availTop: " + screen.availTop + "<br />"); document.writeln("screen.availLeft: " + screen.availLeft + "<br />"); document.writeln("screen.availWidth: " + screen.availWidth + "<br />"); document.writeln("screen.availHeight: " + screen.availHeight + "<br />"); document.writeln("screen.colorDepth: " + screen.colorDepth + "<br />"); document.writeln("screen.pixelDepth: " + screen.pixelDepth + "<br />"); </script></body></html>

screen.availWidth:
<html> <script language="JavaScript1.2"> <!-document.write("The available width of this user's screen is <b>"); document.write(screen.availWidth + '</b> pixels'); --> </script></html>

screen.colorDepth:
<html><head><title>History</title></head><body><script type="text/javascript"> document.writeln("screen.availTop: " + screen.availTop + "<br />"); document.writeln("screen.availLeft: " + screen.availLeft + "<br />"); document.writeln("screen.availWidth: " + screen.availWidth + "<br />"); document.writeln("screen.availHeight: " + screen.availHeight + "<br />"); document.writeln("screen.colorDepth: " + screen.colorDepth + "<br />"); document.writeln("screen.pixelDepth: " + screen.pixelDepth + "<br />"); </script></body></html>

screen.height:
<html><script language="JavaScript1.2"> <!-document.write("The height of this user's screen is <b>"); document.write(screen.height + '</b> pixels'); --></script></html>

Screen.pixelDepth:
<html><script language="JavaScript1.2"> <!-document.write("The pixel depth of this user's screen is <b>"); document.write(screen.pixelDepth + '</b> bit'); --> </script></html> screen.width <html><script language="JavaScript1.2"> <!-document.write("The width of this user's screen is <b>"); document.write(screen.width + '</b> pixels'); --> </script></html> History The History object allows you to navigate through the history of Websites that a browser has displayed. The browser stores a history of visited URLs in a list, which the History object references. Properties and Methods of the History Object Property Description back() Loads the URL for the previous visited Web site current Refers to the current URL in the history list forward() Loads the next URL in the history list go() Loads a URL from the history list length Returns the number of entries in the history list next Refers to the next URL in the history list previous Refers to the previous URL in the history list <html><head> <title> Using the history object to view a list of the browser history</title> <script language="JavaScript"> <!-netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead"); --> </head> <body><script language="JavaScript"> <!-for (i=0; i<history.length; i++){ document.writeln(window.history.previous); } //End Hide --></script> </body></html>

History.back():

<html> <head> <title> Using the back method of the History object</title> </head><body><form name=form1> Click on the button to go back to the previous page. <input type="button" value="Go Back" onClick='window.history.back()'> </form></body></html> History.current:

The current property contains a string that specifies the complete URL of the current history entry:.
<html> <head> <title> Using the current property of the History object</title> </head> <body><script language="JavaScript"> <!-netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead"); --> </script><form name=form1> <input type="button" value="Get Current" onClick='alert(window.history.current)'> </form></body></html>

History.forward(): <html><head><title> Using

the forward method of the History object</title> </head><body><form name=form1> Click on the button to go to the forward browser page. <input type="button" value="Go Forward" onClick='window.history.forward()'> </form></body></html>

History.go():

Syntax history.go(num)

The go() method of the History object loads a URL from the history list:
<html><head><title> Using the go method of the History object</title> </head><body><form name=form1> Click on the button to go back 2 pages. <input type="button" value="Go" onClick='window.history.go(-2)'> </form> </body> </html>

History.go(-2):
<html><head><title>History</title></head><body> <h1>history object</h1> <a href="" onclick="history.back();return false">history.back()</a><br /> <a href="" onclick="history.go(-2);return false">history.go(-2)</a><br /><br /> <a href="" onclick="history.forward();return false">history.forward()</a><br /> </script></body></html>

History.length:
The length property is used to get the number of URLs in the history list. <html><head> <title> Using the length property of the History object</title></head><body> <script language="JavaScript"> <!-var numOfURL = window.history.length; document.write("The number of URL's in the history list is: " + numOfURL); --> </script> </body></html> History.next:

The next property is used to get the URL for the next entry in the history list:
<html><head><title> Using the next property of the History object</title> </head> <body><script language="JavaScript"> <!-netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead"); var nextURL = window.history.next; document.write("The next URL in the history list is: " + nextURL); --> </script></body></html>

History.previous:
<html><head><title> Using the previous property of the History object</title> </head><body><script language="JavaScript"> <!-netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead"); --> </script><form name=form1> <input type="button" value="Get Previous" onClick='alert(window.history.previous)'> </form></body></html> Simulated Back and Forward Buttons by using the history object: <html><head> <title>Simulated Back and Forward Buttons</title> </head><body> <h1>Simulated Back and Forward Buttons</h1> <P><a href="javascript:history.back()">Back</a> | <a href="javascript:history.forward()">Forward</a></p> </body></html>

Drag Drop Event:

No drop target events fire:


<html> <head><title>System Drag And Drop Example</title><script type="text/javascript"> function handleDragDropEvent(oEvent) { var oTextbox = document.getElementById("txt1"); oTextbox.value += oEvent.type + "\n"; } </script> </head> <body> <P>Try dragging the text from the textbox to the red square. No drop target events fire.</p> <P>Drag me</p> <div style="background-color: red; height: 100px; width: 100px" ondragenter="handleDragDropEvent(event)" ondragover="handleDragDropEvent(event)" ondragleave="handleDragDropEvent(event)" ondrop="handleDragDropEvent(event)"></div></p> <P><textarea rows="10" cols="25" id="txt1"></textarea></p> </body></html>

2. Drop target events fire now


<html> <head> <title>System Drag And Drop Example</title><script type="text/javascript"> function handleDragDropEvent(oEvent) { var oTextbox = document.getElementById("txt1"); oTextbox.value += oEvent.type + "\n"; switch(oEvent.type) { case "dragover": case "dragenter": oEvent.returnValue = false; } } </script> </head> <body> <P>Try dragging the text from the textbox to the red square. Drop target events fire now.</p> <P>drag me</p> <div style="background-color: red; height: 100px; width: 100px" ondragenter="handleDragDropEvent(event)" ondragover="handleDragDropEvent(event)" ondragleave="handleDragDropEvent(event)" ondrop="handleDragDropEvent(event)"></div></p> <P><textarea rows="10" cols="25" readonly="readonly" id="txt1"></textarea></p></body></html>

3. Get text object from dataTransfer defined the Drag and drop event
<html><head><title>System Drag And Drop Example</title><script type="text/javascript"> function handleDragDropEvent(oEvent) { switch(oEvent.type) { case "dragover": case "dragenter": oEvent.returnValue = false; break; case "drop": alert(oEvent.dataTransfer.getData("text")); } } </script> </head><body> <P>show you the selected text when dropped.</p> <P><input type="text" value="drag this text" /> <input type="test" ondragenter="handleDragDropEvent(event)" ondragover="handleDragDropEvent(event)" ondrop="handleDragDropEvent(event)"></input></p> </body></html>

4.Get URL object from dataTransfer defined the Drag and drop event:
<html><head> <title>System Drag And Drop Example</title><script type="text/javascript"> function handleDragDropEvent(oEvent) { switch(oEvent.type) { case "dragover": case "dragenter": oEvent.returnValue = false; break; case "drop": alert(oEvent.dataTransfer.getData("URL"));

} } </script></head> <body> <P>Try dragging the link to the red square. It will show you the URL when dropped.</p> <P><a href="http://www.java2s.com">www.java2s.com</a> <input type="text" ondragenter="handleDragDropEvent(event)" ondragover="handleDragDropEvent(event)" ondrop="handleDragDropEvent(event)"></div></p></body></html>

5.Get drag and drop event type: dragstart


<html><head> <title>System Drag And Drop Example</title><script type="text/javascript"> function handleDragDropoEvent(oEvent) { switch(oEvent.type) { case "dragstart": oEvent.dataTransfer.effectAllowed = "move"; alert("dragstart"); break; } } </script></head><body> <P>Try dragging the text in the textbox to the right textbox.</p> <P><input type="text" value="drag this text" ondragstart="handleDragDropoEvent(event)" /> <input ondragenter="handleDragDropoEvent(event)" ondragover="handleDragDropoEvent(event)" ondrop="handleDragDropoEvent(event)"> </input> </p> </body></html>

6. Get drag and drop event type: dragenter


<html><head><title>System Drag And Drop Example</title> <script type="text/javascript"> function handleDragDropoEvent(oEvent) { switch(oEvent.type) { case "dragenter": oEvent.dataTransfer.dropEffect = "move"; break; } } </script></head><body> <P>Try dragging the text in the textbox to the right textbox.</p> <P><input type="text" value="drag this text" ondragstart="handleDragDropoEvent(event)" /> <input ondragenter="handleDragDropoEvent(event)" ondragover="handleDragDropoEvent(event)" ondrop="handleDragDropoEvent(event)"> </input></p></body></html>

7.Get drag and drop event type: dragover


<html><head><title>System Drag And Drop Example</title><script type="text/javascript"> function handleDragDropoEvent(oEvent) { switch(oEvent.type) { case "dragover": oEvent.returnValue = false; break; } } </script></head><body> <P>Try dragging the text in the textbox to the right textbox.</p> <P><input type="text" value="drag this text" ondragstart="handleDragDropoEvent(event)" /> <input ondragenter="handleDragDropoEvent(event)" ondragover="handleDragDropoEvent(event)" ondrop="handleDragDropoEvent(event)"></input> </p></body></html> 8.

Get drag and drop event type: drop

<html><head><title>System Drag And Drop Example</title> <script type="text/javascript"> function handleDragDropoEvent(oEvent) {

switch(oEvent.type) { case "drop": oEvent.returnValue = false; oEvent.srcElement.innerHTML = oEvent.dataTransfer.getData("text"); } } </script> </head> <body> <P>Try dragging the text in the textbox to the right textbox.</p> <P><input type="text" value="drag this text" ondragstart="handleDragDropoEvent(event)" /> <input ondragenter="handleDragDropoEvent(event)" ondragover="handleDragDropoEvent(event)" ondrop="handleDragDropoEvent(event)"> </input> </p></body></html>

1. System Drag And Drop between two text boxes

<html><head> <title>System Drag And Drop between two text boxes</title><script type="text/javascript"> function handleDragDropEvent(oEvent) { var oTextbox = document.getElementById("txt1"); oTextbox.value += oEvent.type + "\n"; } </script></head><body> <P>Try dragging the text from the left textbox to the right one.</p> <P> <input type="text" value="drag this text" ondragstart="handleDragDropEvent(event)" ondrag="handleDragDropEvent(event)" ondragend="handleDragDropEvent(event)" /> <input type="text" ondragenter="handleDragDropEvent(event)" ondragover="handleDragDropEvent(event)" ondragleave="handleDragDropEvent(event)" ondrop="handleDragDropEvent(event)" /> </p> <P><textarea rows="10" cols="25" readonly="readonly" id="txt1"></textarea></p> </body></html>

Style: 1. backgroundColor:
<html><head><title>Style Example</title><script type="text/javascript"> function getColor() { var oDiv = document.getElementById("myDiv"); alert(oDiv.style.backgroundColor); } </script></head><body> <div id="myDiv" style="background-color: red; height: 50px; width: 50px"></div><br /> <input type="button" value="Get Background Color" onclick="getColor()" /></body></html>

2. Get and set node background color:


<html><head><title>The Node</title><script type="text/javascript"> function outputNodeProps(nd) { var strNode = "Node Type: " + nd.nodeType; strNode += "\nNode Name: " + nd.nodeName; strNode += "\nNode Value: " + nd.nodeValue; if (nd.style) { var clr = "red"; nd.style.backgroundColor=clr; strNode += "\nbackgroundColor: " + clr; } alert(strNode); } </script><body onload="outputNodeProps(document)"><div id="div1"><h1>Header</h1></div></body></html>

2. div.style.backgroundColor="#00f";
<html><head><title>PrettyPretty</title><script type="text/javascript"> document.onclick=changeElement; function changeElement() { var div = document.getElementById("div1"); div.style.backgroundColor="#00f";div.style.width="500px";div.style.color="#fff"; div.style.height="200px"; div.style.paddingLeft="50px";div.style.paddingTop="50px";div.style.fontFamily="Verdana";div.style.fontSize="2em"; div.style.border="3px dashed #ff0";div.style.position="absolute";div.style.left="200px"; div.style.top="100px";div.style.textDecoration="underline"; }

</script></head><body><div id="div1"> This is a DIV element. Click me to see the change.</div></body></html> COLOR:

1. Change element color by setting the color style:


<html><head><title>A Simple Page</title><script language="JavaScript"> <!-function colorchange() { head1.style.color = "red"; } function colorchangeback() { head1.style.color = "black"; } // --> </script></head><body><h1 id="head1" onMouseover="colorchange()" onMouseout="colorchangeback()"> Welcome to this page!</h1> <P>A lot of interesting text goes here!</p></body></html>

2.div.style.color="#fff";
<html><head><title>PrettyPretty</title><script type="text/javascript"> document.onclick=changeElement; function changeElement() { var div = document.getElementById("div1"); div.style.backgroundColor="#00f";div.style.width="500px"; div.style.color="#fff";div.style.height="200px"; div.style.paddingLeft="50px";div.style.paddingTop="50px";div.style.fontFamily="Verdana"; div.style.fontSize="2em"; div.style.border="3px dashed #ff0";div.style.position="absolute"; div.style.left="200px";div.style.top="100px";div.style.textDecoration="underline"; } </script></head><body><div id="div1"> This is a DIV element. Click me to see the change.</div></body></html>

Get Computed Style:


<html> <head><title>Computed Style Example</title> <style type="text/css"> div.special { background-color: red; } </style> <script type="text/javascript"> function getBackgroundColor() { var oDiv = document.getElementById("div1"); alert(document.defaultView.getComputedStyle(oDiv, null).backgroundColor); } </script> </head><body> <div id="div1" class="special"></div> <input type="button" value="Get Background Color" onclick="getBackgroundColor()" /> </body></html>

Get cssText:
<html> <head> <title>Style Example</title></head><body><P>Click on the square.</p> <div id="div1" style="background-color: red; height: 50px; width: 50px" onclick="alert(this.style.cssText)"></div> </body></html>

1. element.currentStyle.backgroundColor
This example uses a custom Internet Explorer property and will not work in other browsers. <html> <head><title>Computed Style Example</title><style type="text/css"> div.special { background-color: inherit; } </style><script type="text/javascript"> function getBackgroundColor() {

var oDiv = document.getElementById("div1"); alert(oDiv.currentStyle.backgroundColor); } </script></head><body> <div id="div1" class="special"></div> <input type="button" value="Get Background Color" onclick="getBackgroundColor()" /></body></html>

2. element.currentStyle.height:
This example uses a custom Internet Explorer property and will not work in other browsers. <html><head> <title>Computed Style Example</title><style type="text/css"> div.special { background-color: red; height: 10px; } </style> <script type="text/javascript"> function getBackgroundColor() { var oDiv = document.getElementById("div1"); alert(oDiv.currentStyle.height); } </script></head><body> <div id="div1" class="special"></div> <input type="button" value="Get Background Color" onclick="getBackgroundColor()" /></body></html>

3. element.currentStyle.margin:
This example uses a custom Internet Explorer property and will not work in other browsers. <html><head> <title>Computed Style Example</title><style type="text/css"> div.special { background-color: red; margin: 10px; } </style> <script type="text/javascript"> function getBackgroundColor() { var oDiv = document.getElementById("div1"); alert(oDiv.currentStyle.margin); } </script> </head><body> <div id="div1" class="special"></div> <input type="button" value="Get Background Color" onclick="getBackgroundColor()" /> </body></html>

Show and hide elements (IE):


<html><head><title>A Simple Page</title><script language="JavaScript"> <!-function checkBold() { var thistag, parentTag; thistag = window.event.srcElement.tagName; parentTag = window.event.srcElement.parentElement.tagName; if (thistag == "H1" && parentTag == "BODY") { if(document.all(window.event.srcElement.id + "p").style.display == "none") { document.all(window.event.srcElement.id + "p").style.display = ""; } else { document.all(window.event.srcElement.id + "p").style.display = "none"; } } } // --> </script></head><body onclick="checkBold()"> <h1 id="head1">Heading One</h1> <p id="head1p" style="display:none">111111111111111</p> <h1 id="head2">Heading Two</h1> <p id="head2p" style="display:none">22222222</p>

<h1 id="head3">Heading Three</h1> <p id="head3p" style="display:none">3333</p></body></html> Get style value by property value (IE does not support DOM style methods:<html><head> <title>Style Example</title><script type="text/javascript"> function useMethods() { var oDiv = document.getElementById("myDiv"); alert(oDiv.style.getPropertyValue("background-color")); } </script></head><body><div id="myDiv" style="background-color: red; height: 50px; width: 50px"></div><br /> <input type="button" value="Use Methods" onclick="useMethods()" /></body></html> Get style by item index (IE does not support DOM style methods):<html> <head> <title> Style Example </title> <script type="text/javascript"> function useMethods() { var oDiv = document.getElementById("myDiv"); alert(oDiv.style.item(0)); } </script></head><body><div id="myDiv" style="background-color: red; height: 50px; width: 50px"></div><br /> <input type="button" value="Use Methods" onclick="useMethods()" /></body></html>

1. Change element left position


<html><head><style>div { position:relative; }</style> <title>Animating Text</title> <SCRIPT LANGUAGE="JavaScript" type = "text/javascript">var pos1 = 0; function f() { pos1 += 5; if (pos1 > 640) pos1 = 0; document.getElementById("movetext").style.left = pos1; window.setTimeout("f();",300); } </SCRIPT></head><body onLoad="f();"><div id="movetext"><b>inside a div</b> </div></body></html>

2. div.style.left="200px":
<html><head><title>PrettyPretty</title><script type="text/javascript">document.onclick=changeElement; function changeElement() { var div = document.getElementById("div1");div.style.backgroundColor="#00f";div.style.width="500px"; div.style.color="#fff";div.style.height="200px"; div.style.paddingLeft="50px"; div.style.paddingTop="50px";div.style.fontFamily="Verdana"; div.style.fontSize="2em"; div.style.border="3px dashed #ff0";div.style.position="absolute";div.style.left="200px"; div.style.top="100px";div.style.textDecoration="underline"; } </script></head><body><div id="div1"> This is a DIV element. Click me to see the change.</div></body></html>

1. Animation by changing the pixelLeft (IE):


<html><head><title>A Simple Page</title><script language="JavaScript"> <!-function moveTxt() { if (document.all) { if (ani1.style.pixelLeft < 500) { ani1.style.pixelLeft += 2; setTimeout("moveTxt()", 50); } } else if (document.ani1.left < 500) { document.ani1.left += 2; setTimeout("moveTxt()", 50); } } // --> </script></head><body onLoad="moveTxt()"> <div id="ani1" style="position:absolute;left:10;top:10"> Text ... on the go!</div></body>

1. Animation by changing the style.pixelTop(IE):


<html><head><title>A Simple Page</title><script language="JavaScript"> <!-function moveTxt()

{ if (ani1.style.pixelTop < 500) { ani1.style.pixelTop += 2; setTimeout("moveTxt()", 50); } } // --> </script> </head><body onLoad="moveTxt()"><div id="ani1" style="position:absolute;left:10;top:10"> Text ... on the go!</div></body></html>

Remove a style value by property name:


<html><head><title>Style Example</title><script type="text/javascript"> function useMethods() { var oDiv = document.getElementById("myDiv"); alert(oDiv.style.getPropertyValue("background-color")); oDiv.style.removeProperty("background-color"); alert(oDiv.style.getPropertyValue("background-color")); } </script></head><body><div id="myDiv" style="background-color: red; height: 50px; width: 50px"></div><br /> <input type="button" value="Use Methods" onclick="useMethods()" /> </body></html> Set style by property name:<html><head> <title>Style Example</title></head><body> <div id="div1" style="background-color: red; height: 50px; width: 50px" onmouseover="this.style.setProperty('background-color', 'blue', '')" onmouseout="this.style.setProperty('background-color', 'red', '')"></div></body></html>

1. Change element textDecoration: underline, none, overline:


<html><head><title>A Simple Page</title><script language="JavaScript"> <!-function addunderline() { head1.style.textDecoration = "underline" } function removeunderline() { head1.style.textDecoration = "none" } function addoverline() { head1.style.textDecoration = "overline" } // --> </script></head><body> <h1 id="head1" onMouseover="addunderline()" onMouseout="removeunderline()" onClick="addoverline()">Welcome to this page!</h1> <P>A lot of interesting text goes here!</p> </body></html>

2. Change element textDecoration: line-through:


<html><head><title>A Simple Page</title><script language="JavaScript"> <!-function addunderline() { head1.style.textDecoration = "underline" } function removeunderline() { head1.style.textDecoration = "none" } function addoverline() {

head1.style.textDecoration = "overline" } function addlinethrough() { head1.style.textDecoration = "line-through" } // --> </script></head><body> <h1 id="head1" onMouseover="addunderline()" onMouseout="removeunderline()" onClick="addoverline()" ondblclick="addlinethrough()">Welcome to this page!</h1> <P>A lot of interesting text goes here!</p></body></html>

3. div.style.textDecoration="underline":
<html><head><title>PrettyPretty</title><script type="text/javascript">document.onclick=changeElement; function changeElement() { var div = document.getElementById("div1"); div.style.backgroundColor="#00f"; div.style.width="500px"; div.style.color="#fff"; div.style.height="200px"; div.style.paddingLeft="50px"; div.style.paddingTop="50px"; div.style.fontFamily="Verdana";div.style.fontSize=" 2em";div.style.border="3px dashed #ff0";div.style.position="absolute";div.style.left="200px"; div.style.top="100px"; div.style.textDecoration="underline"; } </script></head><body><div id="div1">This is a DIV element. Click me to see the change.</div></body></html>

1. Set div position in page scroll action:


<html><head> <title>OnScroll Example</title><script type="text/javascript"> window.onscroll = function () { var oWatermark = document.getElementById("divWatermark"); oWatermark.style.top = document.body.scrollTop; } </script></head><body> <P>Try scrolling this window.</p> <div id="divWatermark" style="position: absolute; top: 0px; right: 0px; color: #cccccc; width: 150px; h eight: 30px; background-color: navy">www.java2s.com</div> <P>Line 1</p> <P>Line 2</p><P>Line 3</p><P>Line 4</p><P>Line 5</p> <P>Line 6</p><P>Line 7</p> <P>Line 8</p> <P>Line 9</p> <P>Line 10</p><P>Line 11</p> <P>Line 12</p> </body></html> div.style.top="100px": <html><head><title>PrettyPretty</title><script type="text/javascript"> document.onclick=changeElement; function changeElement() { var div = document.getElementById("div1"); div.style.backgroundColor="#00f"; div.style.width="500px"; div.style.color="#fff"; div.style.height="200px"; div.style.paddingLeft="50px";div.style.paddingTop="50px"; div.style.fontFamily="Verdana";div.style.fontSize="2em"; div.style.border="3px dashed #ff0";div.style.position="absolute"; div.style.left="200px";div.style.top="100px"; div.style.textDecoration="underline"; } </script></head><body><div id="div1"> This is a DIV element. Click me to see the change.</div></body></html>

2.

2. div.style.top="100px";
<html><head><title>PrettyPretty</title><script type="text/javascript"> document.onclick=changeElement; function changeElement() { var div = document.getElementById("div1"); div.style.backgroundColor="#00f";div.style.width="500px";div.style.color="#fff";div.style.height="200px"; div. style.paddingLeft="50px";div.style.paddingTop="50px";div.style.fontFamily="Verdana"; div.style.fontSize="2em"; div.style.border="3px dashed #ff0"; div.style.position="absolute"; div.style.left="200px"; div.style.top="100px"; div.style.textDecoration="underline"; } </script></head><body><div id="div1"> This is a DIV element. Click me to see the change.</div></body></html>

1. div.style.fontFamily="Verdana";
<html><head><title>PrettyPretty</title><script type="text/javascript"> document.onclick=changeElement; function changeElement() { var div = document.getElementById("div1"); div.style.backgroundColor="#00f";div.style.width="500px"; div.style.color="#fff"; div.style.height="200px"; div.style.paddingLeft="50px";div.style.paddingTop="50px"; div.style.fontFamily="Verdana";div.style.fontSize="2em";div.style.border="3px dashed #ff0"; div.style.position="absolute"; div.style.left="200px";div.style.top="100px";div.style.textDecoration="underline"; } </script></head><body><div id="div1"> This is a DIV element. Click me to see the change.</div></body></html> 2.

div.style.fontSize="2em";<html><head><title>PrettyPretty</title><script
document.onclick=changeElement; function changeElement() { var div = document.getElementById("div1");

type="text/javascript">

div.style.backgroundColor="#00f";div.style.width="500px"; div.style.color="#fff"; div.style.height="200px"; div.style.paddingLeft="50px";div.style.paddingTop="50px";div.style.fontFamily="Verdana";div.style.fontSize="2; div.style.border="3px dashed #ff0";div.style.position="absolute"; div.style.left="200px"; div.style.top="100px"; div.style.textDecoration="underline"; } </script></head><body><div id="div1">This is a DIV element. Click me to see the change.</div></body></html>

3. div.style.fontSize="larger";
<html><head><title>PrettyPretty</title><script type="text/javascript"> function bigger() { var div = document.getElementById("div1");div.style.fontSize="larger";div.style.letterSpacing="10px"; div.style.textAlign="justify";div.style.textTransform="uppercase";div.style.fontSize="xx-large"; div.style.fontWeight="900";div.style.lineHeight="40px"; } function smaller() { var div = document.getElementById("div1");div.style.fontSize="smaller";div.style.letterSpacing="normal"; div.style.textAlign="left";div.style.textTransform="none"; div.style.fontSize="medium"; div.style.fontWeight="normal";div.style.lineHeight="normal"; } </script></head><body><a href="javascript:bigger();">bigger</a> <a href="javascript:smaller();">smaller</a> <div id="div1"> <p>p1</p><p>p2</p> </div></body></html> div.style.fontWeight="900"; <html><head><title>PrettyPretty</title><script type="text/javascript"> function bigger() { var div = document.getElementById("div1");div.style.fontSize="larger";div.style.letterSpacing="10px"; div.style.textAlign="justify";div.style.textTransform="uppercase";div.style.fontSize="xx-large"; div.style.fontWeight="900"; div.style.lineHeight="40px"; } function smaller() { var div = document.getElementById("div1");div.style.fontSize="smaller"; div.style.letterSpacing="normal";div.style.textAlign="left"; div.style.textTransform="none"; div.style.fontSize="medium";div.style.fontWeight="normal";div.style.lineHeight="normal"; } </script></head><body> <a href="javascript:bigger();">bigger</a> <a href="javascript:smaller();">smaller</a> <div id="div1"> <p>p1</p> <p>p2</p> </div></body></html>

4.

5. Set font size with form control:


<html><head><script type="text/javascript"> function showWindow() { var txt = document.form1.stringField.value; var sze = ""; sze = document.form1.sizeList.options[document.form1.sizeList.options.selectedIndex].text; txt = txt.fontsize(sze); objWindow = window.open("", "","width=600,height=300");

objWindow.document.write(txt); objWindow.document.close(); } </script></head> <body> <form method="post" name="form1" action="null"> String:<input type="text" size="40" maxlength="256" name="stringField" /> Size: <select name="sizeList" size="1"> <option selected="selected">1</option> <option>2</option><option>3</option><option>4</option> <option>5</option> <option>6</option><option>7</option> </select> <input type="button" name="Show" value="Show" onclick="showWindow()" /> </form></body></html>

6. Set font color with form control:


<html><head><script type="text/javascript"> function showWindow() { var txt = document.form1.stringField.value; var clr = ""; clr = document.form1.colorList.options[document.form1.colorList.options.selectedIndex].text; txt = txt.fontcolor(clr); objWindow = window.open("", "","width=600,height=300");objWindow.document.write(txt); objWindow.document.close(); } </script></head><body> <form method="post" name="form1" action="null"> String:<input type="text" size="40" maxlength="256" name="stringField" /> Color: <select name="colorList" size="1"> <option selected="selected">black</option> <option>green</option> <option>red</option> </select> <input type="button" name="Show" value="Show" onclick="showWindow()" /></form></body></html>

1. div.style.paddingLeft="50px";
2. <html><head><title>PrettyPretty</title><script type="text/javascript"> document.onclick=changeElement; function changeElement() { var div = document.getElementById("div1"); div.style.backgroundColor="#00f"; div.style.width="500px";div.style.color="#fff"; div.style.height="200px";div.style.paddingLeft="50px"; div.style.paddingTop="50px";div.style.fontFamily="Verdana"; div.style.fontSize="2em"; div.style.border="3px dashed #ff0"; div.style.position="absolute"; div.style.left="200px"; div.style.top="100px";div.style.textDecoration="underline"; } </script></head><body><div id="div1"> This is a DIV element. Click me to see the change. </div></body></html

1. div.style.paddingTop="50px";
<html><head><title>PrettyPretty</title><script type="text/javascript"> document.onclick=changeElement; function changeElement() { var div = document.getElementById("div1"); div.style.backgroundColor="#00f"; div.style.width="500px"; div.style.color="#fff"; div.style.height="200px"; div.style.paddingLeft="50px"; div.style.paddingTop="50px"; div.style.fontFamily="Verdana";div.style.fontSize="2em";div.style.border="3px dashed #ff0"; div.style.position="absolute";div.style.left="200px";div.style.top="100px"; div.style.textDecoration="underline"; } </script></head><body><div id="div1">This is a DIV element. Click me to see the change.</div></body></html>

Event

The Event object represents an event. Properties of the Event Object is listed in the following table. Property Description data Array of URL's for dragged and dropped objects height Height of window layerX Horizontal cursor position within layer layerY Vertical cursor position within layer modifiers Bit mask representing modifier keys pageX Horizontal cursor position within Web page pageY Vertical cursor position within Web page screenX Horizontal cursor position within computer screen screenY Vertical cursor position within computer screen target Object for captured events type Type of event which The mouse button that is pressed width Width of window In addition to the Event properties, events exist that get handled. The available events are shown in the following Table. Events Description ABORT Loading of Web page interrupted by user. BLUR Focus is removed from the object. CHANGE Contents or setting for document object changed. CLICK Mouse button is clicked once. DBLCLICK Mouse button is clicked twice. DRAGDROP Object is dragged and dropped. ERROR Error occurred during loading. FOCUS Focus is applied to an object. KEYDOWN A key is pressed down. KEYPRESS A key is pressed. KEYUP A key is let up after being pressed down. LOAD Load document within a browser. MOUSEDOWN The mouse button is pressed down. MOUSEMOVE The mouse cursor is moved. MOUSEOUT The mouse cursor is moved away from a specific object. MOUSEOVER The mouse cursor is moved over a specific object. MOUSEUP The pressed mouse button is let up. MOVE Object is moved on the screen. RESET Reset button is pressed. RESIZE Window or frame has been resized. SELECT Document object is selected. SUBMIT Submit button is pressed. UNLOAD Document is unloaded from browser. <html> <head><title>Using the event object</title> </head> <body> <script language = "Javascript"> <!-window.captureEvents(Event.KEYPRESS | Event.DBLCLICK); document.captureEvents(Event.SUBMIT); function handlePress(evnt){ alert("You pressed a key down. The event type: " + evnt.type); return true; } function handleDblClick(evnt){ alert("You double clicked at location: " + evnt.pageX + "," + evnt.pageY); return(true); } function handleSubmit(evnt){ alert("You clicked on the submit button"); }

window.onkeypress = handlePress; window.ondblclick = handleDblClick; document.onsubmit = handleSubmit; --> </script> When you click on the submit button, it triggers the <b>SUBMIT</b> event which displays an alert box. <br><br> If you double click somewhere in the page, it triggers the <b>DBLCLICK</b> event. <br><br> When a key is pressed down in the browser, the <b>KEYPRESS</b> event is triggered. <br><br><br> <form> <input type="submit" value="Submit" onSubmit=''> </form></body> </html>

event.data:
<html><head> <title>Example of the event.data property</title></head> <body><script language="JavaScript"> <!-function handleDragDrop(evnt){ tmp = new Array(); tmp = evnt.data; alert("The URL for the dragdrop object is: " + tmp); return true; } window.ondblclick = handleDragDrop; --> </script><br><br> Drag and drop an object to the browser.</body></html> event.height: <html> <head><title>Example of the event.height property</title></head><body> <script language = JavaScript> <!-function handle(evnt){ alert("A RESIZE event has occurred. The new height of the window is: " + evnt.height); return true; } window.onresize = handle; --> </script><form name="form1"> Drag the browser border to trigger the resize event</form></body></html>

event.layerX:
<html> <head> <title>Using the layerX property for the event object</title></head><body><script language="JavaSc ript"> <!-function changeSize(){ window.resizeTo(300,400); } function handle(evnt){ alert("The new width (X value) after the resize is: " + evnt.layerX); return true; } window.onresize = handle; --> </script> Drag the browser border to trigger the resize event</body></html>

event.layerY
<html><head><title>Using the layerY property for the event object</title></head><body><script language="JavaScri pt"> <!-function handle(evnt){ alert("The new height (Y value) of the window object after the resize is: " + evnt.layerY); return true; }

window.onresize = handle; --> </script>Resize the browser to see the result. </body></html>

event.pageX:
The pageX property controls the horizontal (x-coordinate) positioning within a Web page. <html><head><title>Example of the event.pageX property</title> </head> <body><script language = "JavaScript"> <!-window.captureEvents(Event.CLICK); function handle(evnt){ alert("The X coordinate of where the click event occurred is: " + evnt.pageX); return true; } window.onclick = handle; --> </script><form> Click in the web browser. </form></body></html>

7. event.pageY:
The pageY property of the Event object controls the vertical (y-coordinate) positioning. <html><head><title>Example of the event.pageY property</title></head><body><script language = "JavaScript"> <!-function handle(evnt){ alert("The Y coordinate of where the click event occurred is: " + evnt.pageY); return true; } window.onclick = handle; --> </script>Click in the web browser.</body></html>

8. event.screenX:
The screenX property controls the horizontal (x-coordinate) positioning within the computer screen. <html><head> <title>Example of the event.screenX property</title> </head><body><script language = "JavaScript"> <!-function handle(evnt){ alert("The X coordinate relative to the computer screen of where the click occurred is: " + evnt.screenX); return true; } window.onclick = handle; --> </script> Click in the web browser. </body></html>

9. event.screenY:

The screenY property controls the vertical (y-coordinate) positioning within the computer screen. <html><head> <title>Example of the event.screenY property</title> </head><body><script language = "JavaScript"> <!-function handle(evnt){ alert("The Y coordinate relative to the computer screen of where the click occurred is: " + evnt.screenY); return true; } window.onclick = handle; </script>Click in the web browser. </body> </html>

10. event.target:

The target property refers to the object on which the event takes place.
<html>

<head> <title>Using the target property of the event object</title></head> <body><script language = "JavaScript"> <!-function whichButton(evnt){ window.captureEvents(evnt.CLICK); alert("The button you pressed was:" + evnt.target.value); } --> </script><form name="form1"> Choose a button and click on it. <br><br> <input type="button" value="Button1" name="Button1" onClick = whichButton(event)> <input type="button" value="Button2" name="Button2" onClick = whichButton(event)> <input type="button" value="Button3" name="Button3" onClick = whichButton(event)> </form></body> </html>

11.event.type:
<html><head><title>Using the type property for the event object</title> </head><body><script language="Javascript"> <!-function handle(evnt){ if(evnt.type == "click"){ document.form1.msg.value += "The click event occurred.\n" } if(evnt.type == "mousedown"){ document.form1.msg.value += "The mousedown event occurred.\n" } if(evnt.type == "keypress"){ document.form1.msg.value += "The keypress event occurred.\n" } return true; } document.onkeypress = handle;document.onclick = handle;document.onmousedown = handle; --> </script> <form name="form1"> This page demonstrates a few different events. Upon events occurring, a message will be displayed in the textarea indicating which event occurred. <br><br><br> <ul> <li><input type="Button" value="Click Me"></li> <br><br> <li> Dummy text area. <input type="text" size="20"> <br> Click mouse in text field. <br><br> </li> <br><br><b>Message output:</b> <textarea name="msg" rows="10" cols="60"></textarea> <br><br><input type="reset" value="Clear"> </form></body></html>

12.event.which:
The which property refers to which key or mouse button was pressed or clicked. The value returned for mouse events is a numeric value 1, 2, or 3, representing the left, middle, and right mouse buttons, respectively. The value returned for keyboard events is a character representation for the key that was pressed. <html><head><title>Using the which property of the event object</title> </head> <body><form> This example uses the which property of the event object to determine which mouse button is pressed. <br><br> <input type="radio" onClick = 'alert("Mouse button Number " + event.which + "was pressed.")'> </form></body> </html>

event.width:
The width property refers to the width of a window or frame. It is set during the RESIZE event to the new width of window or frame being resized. <html><head><title>Example of the event.width property</title> </head> <body><script language = JavaScript>

<!-function handle(evnt){ alert("An RESIZE event has occurred. The new width of the window is: " + evnt.height); return true; } window.onresize = handle; --> </script> Resize browser to see the result</body></html>

Event.ABORT:
The ABORT property is used by images and refers to the event in which a transfer is interrupted or aborted by a use <html> <head><title>Example of Event.ABORT</title></head><body><script language = "JavaScript"> <!-function handleAbort(evnt){ alert("An ABORT event has occurred."); return true; } document.onabort = handleAbort; --> </script></body> </html>

Add event handler to form:


<html><head><title>W3C DOM Event Propagation</title> <script type="text/javascript"> function init() { document.forms[0].addEventListener("click", formBubbleEvent, false); } function formBubbleEvent(evt) { alert("FORM only on BUBBLE."); } function getPhase(evt) { switch (evt.eventPhase) { case 1: return "CAPTURING"; break; case 2: return "AT TARGET"; break; case 3: return "BUBBLING"; break; default: return ""; } } </script> </head> <body onload="init()"> <form> <input type="button" value="Button 'main1'" name="main1" onclick="alert('button (' + getPhase(event) + ') .')" />

> Pass key event as the function parameter:


</form> </body> </html <html><head><title>Key Events Example</title><script type="text/javascript"> function handleEvent(oEvent) { var oTextbox = document.getElementById("txt1"); oTextbox.value += "\n>" + oEvent.type; } </script></head><body> <P>Type some characters into the first textbox.</p> <P><textarea id="txtInput" rows="15" cols="50" onkeydown="handleEvent(event)"onkeyup="handleEvent(event)" onkeypress="handleEvent(event)"></textarea></p> <P><textarea id="txt1" rows="15" cols="50"></textarea></p></body></html>

Use mouse event as the function parameter:


<html><head><title>Mouse Events Example</title><script type="text/javascript"> function handleEvent(oEvent) { var oTextbox = document.getElementById("txt1"); oTextbox.value += "\n" + oEvent.type;

} </script></head><body><P>Use your mouse to click and double click the red square.</p> <div style="width: 100px; height: 100px; background-color: red" onclick="handleEvent(event)" id="div1"></div> <P><textarea id="txt1" rows="15" cols="50"></textarea></p> </body></html>

X/Y Marks the Spot for a popup window (IE):


<html><head><title>X/Y Marks the Spot</title><script type="text/javascript"> function mouseDown() { var locString = "X = " + window.event.screenX + " Y = " + window.event.screenY; document.write(locString); } document.onmousedown=mouseDown;</script></head><body></body></html>

Get event Phase: CAPTURING,BUBBLING:


<html> <head> <title>W3C DOM Event Propagation</title> <script type="text/javascript"> function getPhase(evt) { switch (evt.eventPhase) { case 1: return "CAPTURING"; break; case 2: return "AT TARGET"; break; case 3: return "BUBBLING"; break; default: return ""; } } </script> </head> <body onload="init()"> <form> <input type="button" value="Button 'main1'" name="main1" onclick="alert('button (' + getPhase(event) + ').')" /> </form> </body> </html>Key event type:<html> <head> <title>Key Events Example</title> <script type="text/javascript"> function handleEvent(oEvent) { var oTextbox = document.getElementById("txt1"); oTextbox.value += "\n>" + oEvent.type; } </script> </head><body> <P>Type some characters into the first textbox.</p> <P><textarea id="txtInput" rows="15" cols="50" onkeydown="handleEvent(event)" onkeyup="handleEvent(event)"onkeypress="handleEvent(event)"></textare a></p> <P><textarea id="txt1" rows="15" cols="50"></textarea></p> </body></html>

Get mouse event type: click


<html><head><title>Mouse Events Example</title><script type="text/javascript"> function handleEvent(oEvent) { var oTextbox = document.getElementById("txt1"); oTextbox.value += "\n" + oEvent.type;

} </script></head><body> <P>Use your mouse to click and double click the red square.</p> <div style="width: 100px; height: 100px; background-color: red" onclick="handleEvent(event)" id="div1"></div> <P><textarea id="txt1" rows="15" cols="50"></textarea></p></body></html>

Get mouse event type: onmouseover:


<html><head><title>Mouse Events Example</title><script type="text/javascript"> function handleEvent(oEvent) {

var oTextbox = document.getElementById("txt1"); oTextbox.value += "\n" + oEvent.type;

} </script></head><body><P>Use your mouse to click and double click the red square.</p> <div style="width: 100px; height: 100px; background-color: red" onmouseover="handleEvent(event)" id="div1"></div> <P><textarea id="txt1" rows="15" cols="50"></textarea></p></body></html>

Get mouse event type: onmouseout:


<html><head><title>Mouse Events Example</title><script type="text/javascript"> function handleEvent(oEvent) { var oTextbox = document.getElementById("txt1"); oTextbox.value += "\n" + oEvent.type;

} </script></head><body><P>Use your mouse to click and double click the red square.</p> <div style="width: 100px; height: 100px; background-color: red" onmouseout="handleEvent(event)" id="div1"></div> <P><textarea id="txt1" rows="15" cols="50"></textarea></p></body></html>

Get mouse event type: onmousedown:


<html><head><title>Mouse Events Example</title><script type="text/javascript"> function handleEvent(oEvent) { var oTextbox = document.getElementById("txt1"); oTextbox.value += "\n" + oEvent.type;

} </script></head><body><P>Use your mouse to click and double click the red square.</p> <div style="width: 100px; height: 100px; background-color: red" onmousedown="handleEvent(event)" id="div1"></div> <P><textarea id="txt1" rows="15" cols="50"></textarea></p></body></html>

Get mouse event type: onmouseup:


<html><head><title>Mouse Events Example</title><script type="text/javascript"> function handleEvent(oEvent) { var oTextbox = document.getElementById("txt1"); oTextbox.value += "\n" + oEvent.type; } </script></head><body><P>Use your mouse to click and double click the red square.</p> <div style="width: 100px; height: 100px; background-color: red" onmouseup="handleEvent(event)" id="div1"></div> <P><textarea id="txt1" rows="15" cols="50"></textarea></p></body></html>

Get mouse event type: ondblclick:


<html><head><title>Mouse Events Example</title><script type="text/javascript"> function handleEvent(oEvent) { var oTextbox = document.getElementById("txt1"); oTextbox.value += "\n" + oEvent.type;

} </script></head><body><P>Use your mouse to click and double click the red square.</p> <div style="width: 100px; height: 100px; background-color: red" ondblclick="handleEvent(event)" id="div1"></div> <P><textarea id="txt1" rows="15" cols="50"></textarea></p></body></html>

Get key event target element id:


<html><head><title>Key Events Example</title><script type="text/javascript"> function handleEvent(oEvent) { var oTextbox = document.getElementById("txt1"); oTextbox.value += "\n>" + oEvent.type; oTextbox.value += "\n target is " + (oEvent.target || oEvent.srcElement).id;

} </script></head><body><P>Type some characters into the first textbox.</p> <P><textarea id="txtInput" rows="15" cols="50" onkeypress="handleEvent(event)"></textarea></p> <P><textarea id="txt1" rows="15" cols="50"></textarea></p> </body></html>

Event Bubbling Demonstration:


<html onclick="alert('Event is now at the HTML element.')"> <head> <title>Event Bubbles</title> <script type="text/javascript"> function init() { window.onclick = winEvent document.onclick = docEvent; document.body.onclick = docBodEvent; } function winEvent() { alert("window object level."); } function docEvent() { alert("document object level."); } function docBodEvent() { alert("BODY element."); } </script> </head> <body onload="init()"> <form onclick="alert('FORM')"> <input type="button" value="Button 'main1'" name="main1" onclick="alert('Button: ' + this.name)" /> </form> </body> </html>

Get mouse clicked button:


<html><head><title>Mouse Events Example</title><script type="text/javascript"> function handleEvent(oEvent) { var oTextbox = document.getElementById("txt1"); oTextbox.value += "\n button down is " + oEvent.button; } </script></head><body><P>Use your mouse to click and double click the red square.</p> <div style="width: 100px; height: 100px; background-color: red" onclick="handleEvent(event)" id="div1"></div> <P><textarea id="txt1" rows="15" cols="50"></textarea></p></body></html>

Is Shift key pressed during the mouse click:


<html><head><title>Mouse Events Example</title><script type="text/javascript"> function handleEvent(oEvent) { var oTextbox = document.getElementById("txt1"); oTextbox.value += "\n button down is " + oEvent.button; var arrKeys = []; if (oEvent.shiftKey) { arrKeys.push("Shift"); } oTextbox.value += "\n keys down are " + arrKeys; } </script></head><body> <P>Use your mouse to click and double click the red square.</p> <div style="width: 100px; height: 100px; background-color: red" onclick="handleEvent(event)" id="div1"></div> <P><textarea id="txt1" rows="15" cols="50"></textarea></p></body></html>

Is alt key pressed during the mouse click:


<html><head><title>Mouse Events Example</title><script type="text/javascript"> function handleEvent(oEvent) { var oTextbox = document.getElementById("txt1"); oTextbox.value += "\n button down is " + oEvent.button; var arrKeys = []; if (oEvent.altKey) { arrKeys.push("Alt"); } oTextbox.value += "\n keys down are " + arrKeys;

} </script></head><body><P>Use your mouse to click and double click the red square.</p> <div style="width: 100px; height: 100px; background-color: red" onclick="handleEvent(event)" id="div1"></div> <P><textarea id="txt1" rows="15" cols="50"></textarea></p></body></html>

Is control key pressed during the mouse click:


<html><head><title>Mouse Events Example</title><script type="text/javascript"> function handleEvent(oEvent) { var oTextbox = document.getElementById("txt1"); oTextbox.value += "\n button down is " + oEvent.button; var arrKeys = []; if (oEvent.ctrlKey) { arrKeys.push("Ctrl"); } oTextbox.value += "\n keys down are " + arrKeys; } </script></head><body><P>Use your mouse to click and double click the red square.</p> <div style="width: 100px; height: 100px; background-color: red" onclick="handleEvent(event)" id="div1"></div> <P><textarea id="txt1" rows="15" cols="50"></textarea></p></body></html>

Use mouse in/out action to trigger the style change:


<html><head><title>Style Example</title></head><body> <P>Move your mouse over the square.</p> <div id="div1" style="background-color: red; height: 50px; width: 50px" onmouseover="this.style.backgroundColor = 'blue'" onmouseout="this.style.backgroundColor = 'red'"> </div></body></html>

Get mouse client X and Y:


<html><head><title>Mouse Events Example</title><script type="text/javascript"> function handleEvent(oEvent) { var oTextbox = document.getElementById("txt1"); oTextbox.value += "\n at (" + oEvent.clientX + "," + oEvent.clientY + ") in the client"; } </script></head><body> <P>Use your mouse to click and double click the red square.</p> <div style="width: 100px; height: 100px; background-color: red" onclick="handleEvent(event)" id="div1"></div> <P><textarea id="txt1" rows="15" cols="50"></textarea></p></body></html>

Get mouse screen X and Y:


<html><head><title>Mouse Events Example</title><script type="text/javascript"> function handleEvent(oEvent) { var oTextbox = document.getElementById("txt1"); oTextbox.value += "\n at (" + oEvent.screenX + "," + oEvent.screenY + ") on the screen"; } </script></head><body> <P>Use your mouse to click and double click the red square.</p> <div style="width: 100px; height: 100px; background-color: red" onclick="handleEvent(event)" id="div1"></div> <P><textarea id="txt1" rows="15" cols="50"></textarea></p></body></html>

Functions:

All function declaration must begin with the keyword function followed by the name of the function. Parentheses are placed after the function name to hold arguments. If more than one argument are used, use commas to separate the arguments. If no arguments, leave the space between the parentheses empty. Curly brackets are used to contain the code related to the function.

Curly brackets are not optional.

JavaScript uses call by value.


<html><SCRIPT LANGUAGE='JavaScript'> <!-var aString = "A" var aNumber = 1; function test(aString, aNumber) { aString = "B";aNumber = 2; document.write("<BR><BR><BR><BR><BR>During function call:<BR>"); document.write("aStringCopy=",aString,"<BR>"); document.write("aNumberCopy=",aNumber,"<BR>"); } document.write("<BR><BR><BR><BR><BR>Before function call:<BR>"); document.write("aString=",aString,"<BR>");document.write("aNumber=",aNumber,"<BR>"); test(aString,aNumber); document.write("<BR><BR><BR><BR><BR><BR><BR>After function call:<BR>"); document.write("aString=",aString,"<BR>");document.write("aNumber=",aNumber,"<BR>"); //--> </SCRIPT> </html>

Define the simplest function:


<html><head><title>A Simple Page</title><script language="JavaScript"> <!-function yourMessage() { alert("Your first function!"); } // --> </script></head><body></body></html>

Define a function:
<html><head><title>Function Demo</title> <script language="javascript" type="text/javascript"> <!-function greetVisitor() { var myName = prompt("Name.", ""); alert("Welcome " + myName + "!") } //--> </script></head><body><h1>Function Demo</h1></body></html>

Calculation in function:
<html><head><title>A Simple Page</title><script language="JavaScript"> <!--function inputCels() { var cels = 100; ansFah = doFahCalc(cels); alert(cels + " Degrees Celsius is " + ansFah + " Degrees Fahrenheit"); } function inputFah() { var fah = 100; ansCel = doCelCalc(fah); alert(fah + " Degrees Fahrenheit is " + ansCel + " Degrees Celsius"); } function doCelCalc(fah) { var ans = ((Number(fah) - 32) / 1.8); return (ans); } function doFahCalc(cels) { var ans = ((1.8 * Number(cels)) + 32);

return (ans); } // --> </script></head><body><input type="button" value="Convert Celsius to Fahrenheit" onClick="inputCels();"> <br><br><input type="button" value="Convert Fahrenheit to Celsius" onClick="inputFah();"></body></html>

Recursive function:
<HTML><HEAD> <SCRIPT> function fib (inNum) { if (inNum == 0) var fibNum = 0; else{ if (inNum == 1) fibNum = 1; else{ fibNum = fib(inNum - 2) + fib(inNum - 1); } } return fibNum; } function writeFibs(topFib) { for (var i=0; i <= topFib ; i++) { document.write ("Fib(" + i + ") = " + fib(i) + " <br>"); } } </SCRIPT></HEAD><BODY> <FORM Name="theForm"> <INPUT Type=Text Name="numFibs"> <INPUT Type=Button Value="Show Fibs" onClick='writeFibs(numFibs.value);'></FORM></BODY></HTML>

Function() (capital F):


Syntax var variable = new Function() var variable = new Function(int) var variable = new Function(arg1, ..., argN) Function() is a constructor that creates a Function object. Properties and Methods of the Function Object Property/Method Description apply() Applies method to multiple objects arguments Array reflecting function arguments arity Number of arguments expected by function call() Allows calling of methods belonging to other functions caller Reference to function caller prototype Prototype for a class of objects toSource() Created copy of function object toString() Converts function back to string which defines it <html> <script language="JavaScript"> <!-// Create a function to change background color var setBGColor = new Function(document.bgColor='blue'); --> </script></html>

Function.apply(): Syntax function.apply()


The apply() method is used to apply a method of one object to another object. Using the apply() method keeps developers from rewriting methods for different objects <html><head><title>Example</title></head><body><script type="text/javascript"> function ClassA(sColor) { this.color = sColor;

this.sayColor = function () { alert(this.color); }; } function ClassB(sColor, sName) { ClassA.apply(this, arguments); this.name = sName; this.sayName = function () { alert(this.name); }; } var objA = new ClassA("red");var objB = new ClassB("blue", "Nicholas"); objA.sayColor();objB.sayColor();objB.sayName();</script></body></html>

Function.arguments:
Syntax function.arguments The arguments property is an array that holds the arguments that are passed to a function. The arguments array can only be accessed while inside the function. <html> <body> <script lanuguage="JavaScript"> <!-function foo(a,b) { foobar(123); document.write("Done with function foo" + "<br>"); } function foobar(x) { document.write(foobar.arguments.length + "<br>"); document.write(foobar.arguments.caller.b + "<br>"); } document.write(foo(21,44) + "\n"); --></script> </body></html>

Function.arity:
The arity property represents the number of declared arguments a function expects to receive. The arity property is valid when the language attribute of the script tag is set to JavaScript1.2. <html> <body> <script lanuguage="JavaScript1.2"> <!-function subtract(first, second){ var result = first - second; return result; } document.write("arity = " + subtract.arity + "<br>") document.write("The result of the subtract function is: " + subtract(4,3)); --></script></body></html>

Function.call():
Syntax function.call(this) function.call(this, arg1, arg2, ..., argN) The call() method can call another object's method. Optional arguments can be passed to the method as shown in the second syntactical definition. <html> <script language="JavaScript1.3"> <!-function person (author, name){ this.name = name; this.author = true; } function authors(name, books){

this.books = books; person.call(this, name); } authors.prototype = new person(); var myAuthor = new authors("Allen", 5); --> </script></html>

Function.caller:
<html> <body> <script lanuguage="JavaScript1.1"> <!-function functionB(){ var Boss = true; functionA(); } function functionA(){ myBoss = functionA.caller.name; document.write(myBoss + "<br>"); } functionB(); --> </script> </body></html>

Function.prototype;
Syntax function.prototype.property function.prototype.method The prototype property refers to the object that serves as the prototype from which classes are created. prototype allows you to add new properties of methods to an existing class by adding them to the prototype associated with the constructor of that class. <html><body> <script lanuguage="JavaScript"> <!-var mytask = new String(); function setTask(str){ var task="task a"; if(str != null){ task = str; } return task; } String.prototype.duty = setTask; document.write("The first task is: " + mytask.duty("Nothing") + "<br>"); document.write("The next task is: " + mytask.duty()); --></script> </body></html>

Function.toSource():
The toSource() method can create a copy of an object <html><body> <script lanuguage="JavaScript"> <!-var aString = new String("This is the source"); bString = aString.toSource();document.write(bString); --></script> </body> </html>

Function.toString():
The toString() method is used to convert a function to string. The method converts the function back to the JavaScript source. The converted string includes all aspects of the defined function.

<html> <body> <script lanuguage="JavaScript"> <!-function writeText(){ document.write("Some dummy text"); } var func = writeText.toString(); document.write("The string representation of the writeText"); document.write(" function looks like: " + "<br><br><b>");

document.write(func + "</b>"); --> </script> </body> </html>

Pass value to a function:


<html><head><title>A Simple Page</title><script language="JavaScript"> <!-function yourMessage(quote) { alert(quote); } // --> </script></head><body> <P>Click <input type="button" value="AAA" onClick="yourMessage('AAA')"> for a message!</p> <br> <P>Click <input type="button" value="BBB" onClick="yourMessage('BBB')"> for another message!</p></body></html>

Pass number to a function:


<html><head><title>A Simple Page</title><script language="JavaScript"> <!-function calcAvg() { var inpNum1 = 1;var inpNum2 = 2; var inpNum3 = 3;var inpNum4 = 4; numAvg = doCalcAvg(inpNum1, inpNum2, inpNum3, inpNum4); document.write("The average of the four numbers you entered is: " + numAvg); } function doCalcAvg(inpNum1, inpNum2, inpNum3, inpNum4) { var ans; ans = (Number(inpNum1) + Number(inpNum2) + Number(inpNum3) + Number(inpNum4)) / 4; return (ans); } // --> </script></head><body onLoad="calcAvg();"></body></html>

Pass integer to function:


<html><head><script language="JavaScript" type = "text/javascript"> <!-function DisplayMsg(NumVal) { if (NumVal == 1) { status = "Type your name in the field" ; } if (NumVal == 2) { status = "Type your phone number in the field" } } //--> </script><title>Keyboard Event</title></head><body><form name="form1"> <b>Name:</b>&nbsp; <input type = "text" name = "text1" onFocus="DisplayMsg(1)" size="20"><P><b>Phone:</b> &nbsp; <input type = "text" name = "text2" onFocus="DisplayMsg(2)" size="20"></p></form></body></html>

Pass Form value to a function:


<HTML><HEAD> <TITLE> Add three numbers</TITLE><SCRIPT> function addThreeNums (inOne, inTwo, inThree) { var inOne = Number(inOne); var inTwo = Number(inTwo); var inThree = Number(inThree); return Number(inOne + inTwo + inThree); } </SCRIPT> </HEAD><BODY><FORM Name="theForm"><INPUT Type=Text Name="num1"><INPUT Type=Text Name="num2"> <INPUT Type=Text Name="num3"><INPUT Type=Button Value="Add Them" onClick='document.write("sum:" +addThreeNums(theForm.num1.value,theForm.num2.value,theForm.num3.value));'> </FORM></BODY></HTML>

Use functionName.arguments to reference the arguments:


<HTML><HEAD><TITLE>Add all of the numbers</TITLE><SCRIPT>function addNums () { var theAnswer = 0; for (var i = 0; i < addNums.arguments.length; i++) { var theNum = Number(addNums.arguments[i]);

theAnswer += theNum; } return theAnswer; } </SCRIPT></HEAD><BODY><FORM Name="theForm"><INPUT Type=Text Name="num1"><INPUT Type=Text Name="num2"> <INPUT Type=Text Name="num3"><INPUT Type=Text Name="num4"><INPUT Type=Button Value="Add Them" onClick='document.write(addNums(theForm.num1.value,theForm.num2.value,theForm.num3.value,theForm.num4.value));'> </FORM></BODY></HTML>

Pass an array to a function:


<HTML> <HEAD><TITLE> Iteration Two </TITLE> <SCRIPT> function makeArray() { var myArray = new Array(4); myArray[0] = "A"; myArray[1] = "B"; myArray[2] = "C"; myArray[3] = "D"; return myArray; } function showArray(theArray){ var quote = ""; for (var i = 0; i < theArray.length; i++){ quote += theArray[i] + " "; } return quote; } </SCRIPT></HEAD> <BODY><H1><SCRIPT> var x = makeArray(); document.write(showArray(x)); </SCRIPT></H1></BODY></HTML>

Arguments:
Syntax arguments arguments[index] The Arguments object is an array that contains all the arguments passed into the function. The Arguments object is automatically created and initialized when a function is invoked. The Arguments object goes out of scope when the code function finishes executing. To access arguments passed into a function, simply use array brackets to specify an index. Properties Associated with the Arguments Object is listed in the following table. Property Description callee Contains the function that is currently executing caller Contains the Arguments object of the calling function length The length of the arguments array

<html> <form> <input type="button" value="A" <input type="button" value="B" <input type="button" value="C" <input type="button" value="D" <input type="button" value="E" </form> <script language="JavaScript">

OnClick=displayFood(this,"A")> OnClick=displayFood(this,"B")> OnClick=displayFood(this,"C")> OnClick=displayFood(this,"D")> OnClick=displayFood(this,"E")>

<!-function displayFood() { var aString = arguments[0].value; aString += "'s is "; aString += arguments[1];

alert(aString); } --> </script> </html>

arguments.callee:
The callee property contains the function that is currently executing. This is useful if the function has no name. <html> <form> <input type="button" value="A" OnClick=myFunction(this,"A")> <input type="button" value="B" OnClick=myFunction(this,"B")> <input type="button" value="C" OnClick=myFunction(this,"C")> <input type="button" value="D" OnClick=myFunction(this,"D")> <input type="button" value="E" OnClick=myFunction(this,"E")> </form> <script language="JavaScript"> <!-function myFunction() { var aString = arguments[0].value; aString += "'s is "; aString += arguments[1]; alert(aString); alert(arguments.callee.toString()); } --> </script></html>

arguments.caller:
The caller property contains the Arguments object of the calling function. If the given function was not executed from another function, arguments.caller is null. <html> <form> <input type="button" value="A" <input type="button" value="B" <input type="button" value="C" <input type="button" value="D" <input type="button" value="E" </form> <script language="JavaScript">

OnClick=myFunction(this,"A")> OnClick=myFunction(this,"B")> OnClick=myFunction(this,"C")> OnClick=myFunction(this,"D")> OnClick=myFunction(this,"E")>

<!-function displayArgLength() { var argLengthStr = "The calling function contained "; argLengthStr += arguments.caller.length; argLengthStr += " arguments."; alert(argLengthStr); } function myFunction() { var aString = arguments[0].value; aString += "'s is "; aString += arguments[1]; alert(aString); displayArgLength(); } --></script></html>

arguments.length:
The length property contains the number of arguments that were passed into the function. This number matches the number of elements in the arguments array associated with the Argument object
<html> <form> <input type="button" value="A" OnClick=myFunction(this,"A","B","C")> <input type="button" value="B" OnClick=myFunction(this,"D","E")>

<input type="button" value="C" OnClick=myFunction(this,"F")> <input type="button" value="D" OnClick=myFunction(this,"G","H")> <input type="button" value="E" OnClick=myFunction(this,"I")> </form> <script language="JavaScript"> <!-function myFunction() { var aString = arguments[0].value; aString += "'s are: "; for(var i=1; i<arguments.length; i++) { aString += arguments[i]; aString += ", "; } alert(aString); } --> </script> </html>

Use arguments.callee.toString() to get the source of the function:


<html> <form> <input type="button" value="A" OnClick=displayFood(this,"A")> <input type="button" value="B" OnClick=displayFood(this,"B")> <input type="button" value="C" OnClick=displayFood(this,"C")> <input type="button" value="D" OnClick=displayFood(this,"D")> <input type="button" value="E" OnClick=displayFood(this,"E")> </form> <script language="JavaScript"> <!-function displayFood() { var aString = arguments[0].value; aString += "'s is "; aString += arguments[1];alert(aString); alert(arguments.callee.toString()); } --></script></html>

Accessing Function Arguments with the arguments Array:


<html> <SCRIPT LANGUAGE="JavaScript1.2"> <!-function displayArguments() { document.write("The following arguments were passed:<BR>"); for(i=0; i<arguments.length; i++) { document.write(i," = ",arguments[i],"<BR>"); } } displayArguments(3,"AAA",-7,"BBB"); --></SCRIPT></html>

Get function parameter length:


<html><head><title>Try Catch Example</title> <script type="text/javascript">function addTwoNumbers(a, b) { alert(arguments.length); } var result = addTwoNumbers(90); </script></head><body></body></html>

You might also like