Javascript Samples

Solving the "Hello World" problem in javascript

<html>
<body>

<script type="text/javascript">
document.write("<p><h2>Hello World!</h2>")
</script>

</body>
</html>

Run this script

Here is a demonstration of the use of the date object.

<html>
<body>
<script type="text/javascript">
var d=new Date()
var weekday=new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday")
var monthname=new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec")
document.write("<font size=+3>")
document.write(weekday[d.getDay()] + " ")
document.write(d.getDate() + ". ")
document.write(monthname[d.getMonth()] + " ")
document.write(d.getFullYear())
</script>
</body>
</html>

Run this script

It is often used to implement event driven programming

<html>

<head>
<script type="text/javascript">
function ChangeColor()
{
document.body.bgColor="yellow"
}
</script>
</head>

<body onclick="ChangeColor()">
Click on this document!
</body>

</html>
Run this script

Here is a list of events

onBlur when the window loses the focus
onChange when data in an html control changes (text fields, buttons, etc)
onClick when an element is clicked
onDblClick when a element is double clicked
onError
on Focus
onKeyDown
onKeyPress
on KeyUp
onLoad
onMouseDown
onMouseMove
onMouseOut
onMouseOver
onMouseUp
onMove
onReset
onResize
onSelect
onSubmit
onUnload

Javascript can be used to verify entries in a form before submitting it

<html>
<head>
<script type="text/javascript">
function validate()
{
  x=document.myForm
  at=x.email.value.indexOf("@")
  code=x.code.value
  firstname=x.fname.value
  submitOK="True"

  if (at==-1) 
 {
 alert("Not a valid e-mail!")
 submitOK="False"
 }
if (code<1 || code>5)
 {
 alert("The value must be between 1 and 5")
 submitOK="False"
 }
if (firstname.length>10)
 {
 alert("Your name must be less than 10 characters")
 submitOK="False"
 }
if (submitOK=="False")
 {
 return false
 }
}
</script>
</head>

<body>
<form name="myForm" action="http://cgi2.cs.rpi.edu/~ingallsr/generic.cgi" 
onsubmit="return validate()">
Enter your e-mail: <input type="text" name="email" size="20"><br />
Enter a value from 1 to 5: <input type="text" name="code" size="20"><br />
Enter your name, max 10 chararcters: <input type="text" name="fname" size="20"><br />
<input type="submit" value="Submit"> 
</form>
</body>

</html>

Run this here

HTML DOM objects, because you can think of them as representing a tree.

For example, here is a program to change the size of an image.

<head>
<script type="text/javascript">
function setHeight()
{
var x=document.images
x[0].height="250"
}
</script>
</head>

<body>
<img src="compman.gif" width="107" height="98" />
<form>
<input type="button" onclick="setHeight()" value="Change height of image">
</form>
</body>

</html>

Run this here

Here is a program to modify an anchor (<a>)

<html>

<head>
<script type="text/javascript">
function myHref()
{
document.getElementById('myAnchor').innerText="Go to Linux"  
document.getElementById('myAnchor').href="http://www.linux.com"
}
</script>
</head>

<body>
<a id="myAnchor" href="http://www.microsoft.com">Visit Microsoft</a>
<form>
<input type="button" onclick="myHref()" value="Change URL and text">
</form>
</body>

</html>

Run this here

Note that changing the text only works on Internet Explorer, not on Firefox.

Parsing XML in Internet Explorer

<script type="text/javascript">
var xmlDoc = new ActiveXObject("Microsoft.XMLDOM")
xmlDoc.async="false"
xmlDoc.load("book.xml")
// ....... processing the document goes here
</script>

The line xmlDoc.async="false" assures that the parser will halt execution until the document is fully loaded.

xmlDoc has a member called parseError, which has three fields, errorCode, reason, and line

document.write("<br>Error Code: ")
document.write(xmlDoc.parseError.errorCode)
document.write("<br>Error Reason: ")
document.write(xmlDoc.parseError.reason)
document.write("<br>Error Line: ")
document.write(xmlDoc.parseError.line)

xmlDoc has a member function
nodes = xmlDoc.documentElement.childNodes
This returns an array of nodesthese can be accessed by a call to item(n).

<html>
<head></head>
<body>
<script type="text/javascript">
var xmlDoc = new ActiveXObject("Microsoft.XMLDOM")
xmlDoc.async="false"
xmlDoc.load("book.xml")
nodes = xmlDoc.documentElement.childNodes
document.writeln("There are " + nodes.length + " Nodes<p>");
for(i = 0; i < nodes.length; i++) 
{
    document.writeln(nodes.item(i).nodeName + "<p>")
}
</script>
</body>
</html>

Try this

If we change the phrase nodeName to text, like this
document.writeln(nodes.item(i).text + "<p>")
We get the strings. Try it

Here is another member function
nodes = xmlDoc.getElementsByTagName("tag")

returns an array of all nodes with the tag of its argument

This prints out all of the nodes of book.xml

<html>
<head>
<script type="text/javascript">
function printnode(x)
{
    document.write(x.nodeName + "<p>");
    if (x.hasChildNodes()){
      nodes2 = x.childNodes;
        for (j=0;j<nodes2.length;j++){
           document.write(nodes2.item(j).nodeName+ "<p>")
           document.write("--- " + nodes2.item(j).text + "<p>");
        }
   }
}

</script> 
    
</head>
<body>
<font size=+3>
<script type="text/javascript">
var xmlDoc = new ActiveXObject("Microsoft.XMLDOM")
xmlDoc.async="false"
xmlDoc.load("book.xml")
nodes = xmlDoc.documentElement.childNodes
document.writeln("There are " + nodes.length + " Nodes<p>");
for(i = 0; i < nodes.length; i++) 
{
    n = nodes.item(i);
    printnode(n)
}
</script>
</body>
</html>

Run it here