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 are many built-in predefined objects. For example, 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

Here is a link to the reference for Date

Javascript 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

Javascript has a built-in timer. There is a function setTimeout that takes two arguments, the first is the the name of a function to be called when the timer goes off, and the second argument is the number of milliseconds to wait.

Here is a simple example



<html>
<head>
<script type="text/javascript">
function timedMsg()
{
var t=setTimeout("alert('5 seconds!')",5000)
}
</script>
</head>

<body>
<form>
<input type="button" value="Display timed alertbox!" onClick = "timedMsg()">
</form>
<p>Click on the button above. An alert box will be displayed after 5 seconds.</p>
</body>
</html>
Try it

The DOM HTML Model

HTML objects are referred to as DOM objects, because you can think of them as representing a DOM tree. The root is document, which has one child, the element <html>. This typically has two children <head> and <body>.

There are built-in objects to access each of the components of the document. For example, document.images refers to an array of all of the images in the document, and document.anchors refers to all of the anchors (<a> elements) in the document.

Here is a large example which demonstrates some of the features. You should run this to see what it does, and then look at the source code. Note the similarity to the Dom Parser. All of the undefined children are text.

You can use this to modify anything in the document. 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

It is possible to give any element a name or an id, and you can use the function getElementbyId to access that particular element.

Here is a program that changes the contents of a cell in a table


<html>
<head>
<script type="text/javascript">
function changeContent()
{
var x=document.getElementById('myTable').rows[0].cells
x[0].innerHTML="NEW CONTENT"
}
</script>
</head>

<body>
<table id="myTable" border="1">
<tr>
<td>Row1 cell1</td>
<td>Row1 cell2</td>
</tr>
<tr>
<td>Row2 cell1</td>
<td>Row2 cell2</td>
</tr>
<tr>
<td>Row3 cell1</td>
<td>Row3 cell2</td>
</tr>
</table>
<form>
<input type="button" onclick="changeContent()" value="Change content">
</form>
</body>

</html>

Try it!

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.

The navigator object, which represents the user's browser, has a number of built-in methods which can be used to get information about the browser.

navigator.appName is the name of the browser.
navigator.appVersion returns the version of the browser

Here is some code which displays the name and version of the browser.



<html>
<body>
<script type="text/javascript">
var browser=navigator.appName
var b_version=navigator.appVersion
var version=parseFloat(b_version)
document.write("<h1>Browser name: "+ browser)
document.write("<br />")
document.write("Browser version: "+ version + "</h1>")
</script>
</body>
</html>

Try it

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 nodes. These 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

This code only works in Internet Explorer. Here is code that loads and parses an XML document in either IE or Firefox.



<script type="text/javascript">
var xmlDoc;
function loadXML()
{
// code for IE
if (window.ActiveXObject)
  {
  xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
  xmlDoc.async=false;
  xmlDoc.load("note.xml");
  getmessage();
  }
// code for Mozilla, Firefox, Opera, etc.
else if (document.implementation &&
document.implementation.createDocument)
  {
  xmlDoc=document.implementation.createDocument("","",null);
  xmlDoc.load("note.xml");
  xmlDoc.onload=getmessage;
  }
else
  {
  alert('Your browser cannot handle this script');
  }
}

function getmessage()
// code to do something with the file

</script>
</head>

<body onload="loadXML()">
XSLT in Javascript

It is possible to link an xsl document with an xml document using javascript. Here is some code for this for Internet Explorer.

<html>
<body>

<script type="text/javascript">
// Load XML 
var xml = new ActiveXObject("Microsoft.XMLDOM")
xml.async = false
xml.load("courselist.xml")

// Load the XSL
var xsl = new ActiveXObject("Microsoft.XMLDOM")
xsl.async = false
xsl.load("courselist.xsl")

// Transform
document.write(xml.transformNode(xsl))
</script>

</body>
</html>
To refresh your memory
Here is courselist.xml
and here is the stylesheet courselist.xsl

Try it!

Dave Hollinger's stupid javascript tricks