Software Technologies for the Web
 

Javascript

Javascript (NOT Java) is a scripting language. It is a client-side technology which is embedded into the user's browser. It enables us to create dynamic elements in our web pages. From mouseovers to games, all can be achieved with Javascript. This page will run through some examples of what Javascript can do. If you want more just surf the web, there are hundreds to choose from.

The DOM

The Document Object Model (DOM) is the method by which we can access objects of the web page. We can use it to access objects in the page and manipulate them. The image below illustrates how the DOM is constructed.

The DOM (Shannon 2008)

Objects of the DOM can be addressed using the '.' notation. So by using the above image as an example;

window.document.image

In modern browers you can access objects by the use of the name attribute. So if you had a image declared as
<img src="horse.jpg" name="myHorse" />,
you would access it by;

window.document.myHorse

Unfortunately there is no standard DOM for all browsers. The W3C have developed a standard DOM with many browsers taking it up (Shannon 2008). That is fine for the future, but not very helpful to us now. What works in one browser may not function properly in another. A workaround for this is the use of 'sniffer' programs, discussed below.

Back to top

Sniffers

Sniffer programs are used to detect whether a script we have written will work in a particular browser. The are two main ways of doing this. Firstly we can try and detect the browser type, and code for that type. This in the past has proved unreliable at times. Smaller browsers have been incorrectly identified, leading to scripts failing (Shannon 2008).
A more popular method now is to check if certain variables return true when tested. This method is called ' object detection' If you are using images, check if document.image works, if it does then your script will work.
Don't forget though, users can turn off Javascript in there browsers. So it still pays to add the good old <noscript> tags to let the user know what they are missing.

<noscript>
   If you can see this the Javascript function isn't working.
</noscript>
Back to top

Some Examples

As promised we are now going to run through some examples of what Javascript can do. The original source code of these scripts can be found at squanderette.co.uk.

Back to top

hiThere

This script uses the DOM to write some text to the screen using the write method.

<script language="javascript">
<!--
document.write("<b>My name is Ryan</b><br />");
document.write("<b>I live in willsbridge</b><br />");
document.write("<b>I like watching Scrubs</b><br />");
document.write("<b>I love bacon sarnies</b><br />");
// -->
</script>
<noscript>
You don't have Javascript enabled.
</noscript>

Notice how the Javascript is placed inside HTML comment tags. This hides it and makes sure the browser doesn't try to ouptput it as text.
Also we include some text if JavaScript hasn't been enabled.

See a working example.
Source code is here.

Back to top

Functions

Rather then putting lots of code in our page we can create functions that receive parameters and if required return values. When doing this we have two choices, especially useful when using the same code lots of times.
One is to put the code in the <head> tags. The first example does this, receiving two strings (aString and bString) and displaying them in an alert box.. The alert box will hold up any other processing until the user has closed it.

<head>
<script language="javascript">
<!--
// Using Functions
function myAlert(aString, bString)
{
window.alert("Return value is: " + aString + bString);
}
-->
</script>
</head>

We call this function in the page by calling it and passing the parameters in the parenthesis ( ).

<body>
<script language="javascript">
<!--
// Call functions and pass parameters
myAlert("34", "\nWhat is 34 X 2?");
//-->
</script>

We can ask a function to return a value as well. This value may be assigned to a variable so it can be processed.
The code snippet below shows how this would be done:

<html>
<head>
<script language="javascript">
<!--
function myAlert2(aString)
{
//this function takes parameter
// it also returns a value
window.alert(aString);
// return statement below
return (34 * 2);
}
-->
</script>
</head>
<body>
<script language="javascript">
<!--
result = myAlert2("The answer will appear soon");
document.write("The return value was: " + result);
</body>
</html>

The next trick is will be to join some strings together using an external script.
First the script.

// function to join 2 strings
function catStrings(aString, bString)
{
// join variables together (concatinate)
var cString = aString + " != " + bString;
//return final string
return cString;
}

We used the '+' symbol to join the strings together (also known as concatenation).
This code is saved into a seperate file with a .js extension.
We call this file into our HTML page using the src attribute of the script tag.

<body>
<!-- using an external script -->
<script language="Javascript" type="text/javascript"
   src="unit4/function.js">
</script>
</body>

See a working example. of all these functions
Source code of html page is here.
Source code of js file is here.

Back to top

Popups

Many think these are the bain of the Internet. There you are just surfing away when you suddenly get hit by several pop-ups. Even so, they can be used for good. They come in three flavours;

  • alert - message display
  • confirm - yes/no
  • prompt - ask for input

All of these will prevent further action until they have been acknowledged by the user (this is called modal).
This script is going to demonstrate all of these by asking the user to enter a URL, and then it will automatically load that page.
The new function being used here is the location function. This is used to redirect the user to another page.

<script language="javascript">
<!--
function thinkURL() { // ALERT
window.alert("*****************\n" + "Think of another URL\n\n" + "*****************" );
}

function thoughtURL() { // CONFIRM
if (! confirm("Have you thought of one?")) {
window.alert("I can't redirect you then\nBye");
} else { //PROMPT
var URL = prompt("Enter the URL", "www.uwe.ac.uk");
newURL(URL);
}
}

function newURL(URL) {
//check if full address been entered
if (!URL.match(/^http:\/\//))
{
//add protocol if missing
fullAddress = "http://" + URL;
}
else
{
fullAddress = URL;
}
// loads new page in 3 seconds (3 X 1000)
setTimeout("location.replace(fullAddress)",3000);
}

We activate the alert function (thinkURL) by using the onload method.
The hyperlink call the thoughtURL function.

<body onLoad="thinkURL()">
<h1>And today's nonsense is ...</h1>
<p>
Think of another URL and then
<a href="#" onClick="thoughtURL();
return false">click here</a> </p>
</body>

See a working example. of this script.
Source code of html page is here.

Back to top

Objects

Objects in Javascript are a bit different from those in traditional object orientated languages. They are often used as data stores. The DOM can be used to gives us objects, for example document. With these objects there are a number of built-in methods that can be used, for example the write method that we have used in the above scripts.
The example script that is going to be demonstrated now will show how an object can be constructed and manipulated. As mentioned before objects in Javascript are often data stores, this example is going to use an array to store the data and show methods associated with them.

As always we set-up the script in the <head> tag. We start by defining some global variables. We do this by declaring them outside of any of the functions. By doing this we allow them to be accessed by all the functions, they exist through-out the entire script in all functions.
N.B. Be careful, any of the functions may overwrite the current value held!

// a global variable
var tourOperator = "U R Lost Tours";
// create global array
var holidays = [ ];

Notice how we declare an array by using the square brackets [ ].
Having defined an array, we now to setup the object that uses the array. Remember in Javascript objects are functions.
Our object (function) defines the elements of the array we have called Holiday

function Holiday(destination, duration, cost)
{
this.destination = destination;
this.duration = duration;
this.cost = cost;
this.agent = tourOperator;
// tourOperator is a global variable
}

In the above snippet the command this means that the elements we are defining belong to the object (or in our case the function) in which they are called.
Also notice how we call into the object one of the global variables we define earlier.

Now we have our object (the array we have just declared) we need to be able to populate it. Arrays have two methods commonly associated with them, these are
push - add to end of array, and
pop - remove from end of the array.
As we want to add to our array, we will need to use the push method. This is called using the dot notation.

function makeHoliday(dest, dur, cost)
{
// create new array element
hol = new Holiday(dest, dur, cost);
// use array method push to add to array
holidays.push(hol);
}

Adding to the array is a two part action. The function has to create a new element of the array using the parameters passed, then add this to the array using the push method.

We now have the function to create and add to our object, all that is left is to be able to display the data.
This seems easy, we just loop over the array elements displaying each one. The problem here is we might not know how many elements are in the array. This can be solved by using the length property of the array. This method calculates the length of the array. But beware, as with most things in computing counting starts at zero!! We can use the length of the array to mark the end of the loop as we step our way through it.
So now we can access each element, but we need to be able to display each property of each element. We do this by calling another function that can break done each element into the properties we defined when creating the array. These two functions are coded such;

function outputAllHolidays()
{
// loop over array
// start at 0, until array length
for ( var i=0; i<holidays.length; i++)
{
// call display function
outputObject(holidays[i]);
}
}

function outputObject(anObject)
{
document.write("<table border=\"2\" width=\"300px\">");
// for each property, f
for (f in anObject)
{
document.write("<tr><th width=\"100px\">" + f + "</th><td>" + anObject[f] + "</td></tr>");
}
document.write("</table><br />");
}

Now we have finished setting up our object, we can use it in the main body of our web page.
We call the function to create an object, passing the parameters to create it

makeHoliday("Bristol", "4 Weeks", "$100");

Then call the function to display it.

outputAllHolidays();

See a working example. of this script.
Source code of html page is here.

Back to top

Form Validation

For many this is the classic use for Javascript, form validation. As many programmers know, "don't trust users". If you want the user to input their age you may assume that they will use a number, but there will be at least one who tries to type it in. With this act they manage to crash the program dealing with the form input. So to guard against this we can use Javascript to help validate the input before it is sent.
The advantage to this is that it is done client-side, at the users machine. This means that no extra time is wasted having to send the form to the server, check it, and if required back to the user because they have made a mistake. The disadvantage is that the user has the ability turn Javascript off, so remember it still pays to validate any input server-side before it is processed.

Create Form

The first task we have to do is to construct the actual form. The important aspect not to forget is the inclusion of the name attribute. Without this performing validation using Javascript would be difficult.

<textarea name="chat" rows=5 cols=20></textarea>

For a copy of just the form click here.

Add Validation

Check if empty

This example is just going to show you some basic validation. The first check we make is to ensure that the user has completed all the fields. We perform this in two parts; with the name fields we check if any text has been entered, if not we assign a name for them.

/* check if first name option empty, call function
noValue passing the element in DOM notation*/
// where q = form name
// where qc = textarea name
function checkFormSubmit()
{
if ( noValue(q.firstName.value) )
{
// display message to textbox
qc.value += "What no first name? - I shall call you Bill\n";
// assign name to element
q.firstName.value = "Bill";
}
}
// function to check if any content
function noValue(val)
{
// javascript uses the regular expressions from perl
// Sebesta 4.12.1
if (val.search(/\w/) == -1)
// \w switch matches any char/int
{
// this fufils logic in checkFormSubmit call
return true;
}
return false;
} //noValue

Beware of the reverse logic. noValue is testing if empty, therefore returns true if empty. This then executes the code inside of the selection statement of checkFormSubmit.
We repeat this for the last name.

The other check we perform is to just test if the elements have been entered by the user. This is somewhat unnecessary as questions 2,3, and 4 have an initial selection coded into them.
We check the other elements by iterating over them each in turn, again using the DOM notation.

// where q = form name
// where qc = textarea name
function checkText(q, qc)
{
//Warn if text boxes are empty (alphanumeric is OK)
//qc.value += "checkText\n";
for ( var i =0 ; i < q.length; i++)
{
// calls noValue function (again)
if (noValue(q.elements[i].value))
{
qc.value += "No value: "+ q.elements[i].name + "\n";
}
}
}

Check age

The other field we want to check is that of age. The checks we want to perform here is that it is a numeric character and that it is in an acceptable range. The range we are going to use for this is between 10 and 99.
The best way to perform this is by using regular expressions (also known as regex's). Regexs are pattern matching, they can be used to in a variety of ways. We are going to use them to check if a pattern can be matched (the age range). The syntax for Javascript regex is similar to those of Perl (as this is where they stem from).

if (!q.age.value.match(/^[1-9][0-9]$/))
{
myAlert2(" Age between 10 and 99");
qc.value += "Age between 10 and 99\nAge is not in numbers.\n";
return false;
}

The function above executes if the regex is false (note the not symbol !), and if it is runs the myAlert function that displays an alert pop-up box. The actual regex breaks down like this;

  • ^[1-9] - checks that the first character (specified by the ^) is in the range 1 to 9
  • [0-9]$ - checks that the last character (specified by the $) is in the range 0 to 9

By specifying the first and last characters we are saying that they both must exist. This eliminates single inputs (and therefore age below 10) and three digit inputs (ages over 99). Using [0-9] as our regex wouldn't work. This would only check is any of the characters was a number. This would allow an input of thr3e, as it contains a number in the range.

Process Form

Now we have our completed validation script we can apply it to the form. We do this by adding an event trigger in the opening <form> tag.

onSubmit="return checkFormSubmit();

Now when the user clicks on the submit button it will evoke the script. If all goes well the script will return true and it will be sent as per the action attribute. In this case the form submits to itself (remember unit 3 - PHP) where it processes the fields and displays them.

See a working example. of this script.
Source code of html page is here.

Back to top

References

Back to top