Course Content‎ > ‎

Section 03: Client-side Development (II)


During the later half of 1995, a new scripting language project began brewing at Netscape. Initially born under the name LiveScript, the language was developed in parallel with Netscape's Web server software. LiveScript scripts could be used to enhance web pages in a number of ways. For example, an author could use LiveScript to make sure that the information a user entered into a form would be of the proper type. Traditionally, data validation was performed at the server or database level, requiring data exchanges between the client browser and the server. LiveScript would allow the user's computer to handle all of the calculation and verification work, hence moving this stage to the client-side. In early December 1995, Netscape and Sun jointly announced that the scripting language would thereafter be known as JavaScript and Sun would become part of the development team to take the language into the future.

Introduction to Javascript

Perhaps one of the best descriptions of JavaScript was provided in the original press release in 1995:

"JavaScript is an easy-to-use object scripting language designed for creating live online applications that link together objects and resources of both clients and servers. While Java is used by programmers to create new objects and applets, JavaScript is designed for use by HTML page authors and enterprise application developers to dynamically script the behaviour of objects running on either the client or the server. JavaScript is analogous to Visual Basic in that it can be used by people with little or no programming experience to quickly construct complex applications. JavaScript's design represents the next generation of software designed specifically for the Internet and is:

  • designed for creating network-centric applications

  • complementary to and integrated with Java

  • complementary to and integrated with HTML

  • open and cross-platform

JavaScript is an open, freely licensed proposed standard available to the entire Internet community."

JavaScript is an object-based interpreted scripting language that is embedded into HTML pages. With it you can control and program elements of your own Web pages on the client side without depending on server-side scripts or applications. Using JavaScript it is possible to design your own windows, create forms to capture input from users of your Web page, perform mathematical and statistical calculations, and to connect to existing Java applets and plug-ins.

The naming of LiveScript as JavaScript has caused much confusion to both the Java and HTML scripting worlds over the past number of years. In truth, Java and JavaScript are more different than they are similar:

  • Java is a full-blown programming language with a huge and open-ended vocabulary. JavaScript has a much smaller vocabulary and more easily digestible programming model, borrowing much of its syntax from the Java language, but also using elements from the Awk and Perl scripting languages.

  • The reason that we call the JavaScript language object-based is that, although it uses objects, it does not contain the complete functionality of object-oriented compiled programming languages such as C++ and Java.

  • Java support in browsers did not actually arrive for some time after JavaScript was supported. Whereas JavaScript support shipped in every platform-specific version of Navigator 2 in February 1996, Java was not available for Windows 3.1 users until late in the life of Navigator 3.

  • Whereas Java applications run in the Java Virtual Machine (plugin in the case of applets) JavaScript code is interpreted and displayed on a browser that is JavaScript-enabled. During the "Browser Wars" of the late 90s, this caused considerable cross-browser issues!

Browser Wars

While compiling the module notes I came across a page (since expired), which had an interesting self-titled "rant" a snippet of which is:

“ As a person who likes making websites, do the browser wars bug me? Oh no, I just love having to chase up weird, esoteric redirection scripts, making multiple versions of pages, and watching my latest "brilliant" idea look like garbage thanks to the greed, selfishness and sheer bloody-minded testosterone-fuelled competitiveness of the various companies that make web browsers. ”

While possibly a little cynical (and definately sarcastic), the statement was not far off the mark. Because JavaScript is an interpreted language, it relies on the ability of the browser to interpret the code correctly in an "open and cross-platform" (as the press release states!) way. During the late 90s, the two main players in the game were Microsoft and Netscape, who were both striving to be Browser #1 (believe it or not Netscape used to be *way* more popular). During this process of churning out browser versions at maximum speed, the JavaScript "standard" was frequently ignored and often not implemented. Indeed, this was frequently the case with recommended HTML standards also, which accounts for much of the success and respect of the World Wide Web Consortium (W3C). The result of this, was that while you might design your HTML and JavaScript with one browser in mind, users of your site might have reduced or even complete lack of functionality using a different browser. Indeed, to make issues more complex, Microsoft decided to implement its own "JScript" interpreter, which it claimed was "an open implementation of JavaScript".  Things got complicated for web developers to say the least.  

Thankfully, since the release of Netscape 6 and Internet Explorer 5.5 the situation has vastly improved. Many web developers are still tainted by their experiences during the Browser Wars years and even today use JavaScript sparingly or not at all. JavaScript's tainted history has probably provided the strongest recommendation possible for developing on the server side. So why not use JavaScript freely now that the browser wars have settled down considerably? Well this really comes back to the arguments between server and client-side (discussed in the first few pages of the module) but it is possible to reach some sort of hybridisation, which is frequently used.

The ACID Tests for Browsers

Not specifically focused on JavaScript, it is probably a good time to mention the 'Web Standards Project'.  The Web Standards Project is made up of a group of professional web developers who wish to encourage the use of the proper standards in web browsers.  They encourage the simplification of standards, improvement of accessibility and general improvements of the uptake of standards by browser companies.  

To aid in these goals, they have developed a number of tests known as the 'ACID Tests' which allow testing of browsers to check their compatibility with various standards.  For example, ACID 1 allowed testing for compliance with the HTML4 and CSS1 specifications.  ACID 3 (released 2008) allows testing for compliance with HTML and CSS, but also performs testing of JavaScript and DOM.  

Essentially, it is a webpage which should load up correctly and it provides a "percentage compliance" with standards.  The page performs 100 subtests and tests for their compliance (hence the percentage).  

Try it yourself with your own browser:

On testing with the browsers I have currently installed, I obtain:

Chrome 10.0.648.6 = 100%

Opera 11.00 = 100%

Safari 5.0.3 = 100%

Firefox 3.6.13 = 94%

IE 9 (Beta Release) 9.0.7930 = 93%   (but slow)

IE 8 8.0.6001 = 20%  

Figure 3.1: ACID3 test on Chrome Browser

As can be seen from the results, Microsoft has made huge strides towards compliance with the latest version of its Internet Explorer browser.  Despite the test above being on a beta version, it can be seen how they are finally adhering to common web standards.  This development is obviously welcomed by the web developer/designer communities and should enable easier development in future. 

The Return of Javascript

As was mentioned previously, a large number of developers were discouraged from the use of JavaScript during the late 90s and early 2000s.  This was principally due to the different browser implementations of JavaScript - however, it was also possible to mostly ignore JavaScript in achieving most web site features.  For example, if you wanted to perform form data validation, then you had the choice of performing server-side validation instead, completely eliminating the need to be concerned about client-side support for JavaScript. 

In recent years, Web 2.0 applications and Ajax (Asynchronous JavaScript and XML) have emerged to the forefront of web development.  JavaScript is naturally thoroughly entwined in Ajax and has caused a reemergence of JavaScript in web site applications.  To provide an example of an Ajax application, which requires the use of JavaScript, you only need to look as far as Google Maps.

One of the major factors causing a reemergence of JavaScript is HTML5.  This combined with other factors has led in a push towards richer client-side web pages and previously thin browser clients (using simple html pages) are fattening up by the month!

There are new JavaScript APIs for dealing with all of these new HTML5 features, such as drag and drop, canvas (e.g. clicking on an area of the canvas), local web storage etc.

There are still a small number of individuals who turn JavaScript off by default in browsers.  While web developers should support, as best as possible, clients with such a setting, it is becoming more and more acceptable to require clients to turn on JavaScript in order to use your application.

JavaScript Coding

Introducing JavaScript to Web Pages

JavaScript is denoted in a webpage in a manner such as the following:

<script type="text/javascript">

alert("Hello world!");


It can be placed in two different locations in a web page:

  • In the BODY section : JavaScripts in a page will be executed immediately when the page loads into the browser.  


<script type="text/javascript">

alert("Hello World in an alert box!");
document.write("Hello World on the Page!");


  • In the HEAD section :  JavaScripts in the <head> section are executed when they are called or when some event is triggered.  It is generally good practice to locate most JavaScript in the head section and inside functions.  
<script type="text/javascript">
function showMessage()
alert("onload event occurred");


<body onload="showMessage()">
(Try it out: javascript_head_example.html )

JavaScript code is commonly placed in external files.  This typically occurs when code is to be used on several different web pages (somewhat like the same situation as CSS in an external file).  JavaScript files have the extension .js and should not contain the <script></script> tags.  To use an external link, simply point at the file using the src attribute of the <script> tag. 

<script type="text/javascript" src="abc.js"></script>


There are two ways to add comments to JavaScript files: (similar to Java)
  • Multiline comments start with /* and end with */.  Everything between these indicators is commented out and will not be interpreted by the browser.
 * This function does something.
 * Written by David Molloy
  • One-line comments start with // and the browser will ignore everything on the same line    (we have two single line comments in this example)
// This function does something
// Written by David Molloy


The concept of a variable is one of the fundamentals of every programming language - it is a location for storage for data typically to be used at a later stage in a program.  The action of creating a variable is known as declaring a variable.  We can do this as follows:

var firstName = "John";           // We also assign a value to the first three
var familyName = "Doe";
var userAge = 30;
var somethingElse;

There are a number of JavaScript keywords which cannot be used as variable names, such as 'catch', 'true', 'private','continue', 'this' and so on.  There are quite a number of these, so when choosing names you should ensure that they are reasonably unique.  Is 'age' allowable to use as a variable name? Yes it is, but I wasn't 100% sure and it is better to err on the side of caution.  Clashing with a keyword is one sure way to cause yourself all sorts of strange, head-ache inducing problems.

The JavaScript language is dynamically typed, which means that you do not have to specify its data type. Java on the other hand is a strongly typed language meaning that types of variables must be defined and you cannot assign a different data type to the same variable at a later stage.

This JavaScript code is perfectly acceptable:
var someVariable;
someVariable = 5;
alert("My variable is " + someVariable);
someVariable = "David";
alert("My variable is now " + someVariable);

This Java code is not acceptable  (Note: JAVA)
String someVariable = "Test";
someVariable = false;


Functions are self-contained mini-scripts which can be used to organise blocks of code that recur several times in a script.  So by creating the function, you can use a single command to trigger more complex actions, without needing to repeat the same code a number of times.  In addition, it is possible to create functions which can be used globally by all pages (and include those functions in an external JS file).

The format is as follows:
function functionName(arguments) {
   // function operations here

It is recommended that functions are placed within the <head> section of a page.  Functions may be called using functionName() anywhere within the code.  
Any number of arguments may be passed to a function and an optional return value.  

Let us take an example of a function within a HTML page:
    <title>Testing a JavaScript Function</title>

    function sumTwoValues(a, b) {
        announceValuesToTheWorld(a + b);
    function announceValuesToTheWorld(val) {
        document.getElementById("result").innerHTML = val;
        alert("The sum of the two values is " + val);
        alert("Is the value over 50 " + checkValueOver50(val));

    function checkValueOver50(val) {
        return (val>50);


    <h2>Sum of two Values Example</h2>
    <button onclick="sumTwoValues(17,30)">Sum of 17 + 30</button>  
    And the answer is : <span id="result"></span>  
Source (and output): javascript_function_example.html

In this example, we are providing three different functions for the purpose of demonstration.  The first function (sumTwoValues) takes two arguments (a and b), adds them together and passes the resulting value to the announcement function.  This announcement function performs three actions:
  1. Using DOM locates the <span> element in our page with the very handy getElementById method and changes it's inner html to the value of the val variable.  You can see the effect of this on the webpage itself when it prints out the value 47 in this part of the webpage.
  2. Displays an alert notification showing the value of 47
  3. Displays an alert notification of 'false' indicating that the value is not greater than 50.
The function checkValueOver50() demonstrates both the use of arguments and a return value, simply returning true if the value > 50 and false otherwise.


Frequently when writing software, the developer wishes to execute some code in certain circumstances and other code in other circumstances.  Conditional statements are used for this purpose.  While there are other options (such as switch) we will focus exclusively on the if...else statement.
The format of the if..else statement is:
if (condition_1)
[else if (condition_2)
[else if (condition_n_1)
The [ ] brackets means that this is optional  (e.g. you can have an if..else statement with no else if or else sections).  If the resulting statements have more than one javascript statement, they should be "blocked" inside { } characters.  As you can see, this is identical to the Java syntax so there should be nothing new for any Java experts.

So let us take our previous example and change the checkValueOver50(val) method to a new function (with a more representative name) checkRangeForValue(val).

function checkRangeForValue(val) {
var response;
if (val>50) response = "The value is over 50";
else if (val>40) response = "The value is over 40";
else if ((val<=40)&&(val>=35)) {
response = "The value is less than or equal 40 but also greater or equal 35";
alert("This is just demonstrating blocking of statements inside brackets");
} else {
response = "This number of too small to be concerned about";
return response;

A few small changes were made to the previous example in other places - I changed the numbers for the following demonstration and the name of the function needs to be changed where we call it (since we picked a new name) and the alert message was changed to something which makes more sense.

Source (and output): javascript_function_example2.html

As can be seen, only one of the conditional clauses gets executed.  However, since there is both an if and an else there is a guarantee that one of the clauses will be executed.  
As can also be seen, in the example we introduced a number of comparison operators and one logical operator.  

Main Comparison Operators

 Operator        Description
 ==      Equals
 !=  Doesn't equal
 >  Greater than
 <  Less than
 >=  Greater than or equals
 <=  Less than or equals

WARNING: Do not use = as a comparison operator.  It is a very common mistake and simply attempts to assign the value on the right of the = to the variable on the left.  It does not return true or false which is what we are hoping for with comparison operators.

Main logical operators

 Operator      Description
 &&  Logical AND e.g.  (a==b)&&(c!=d) 
 ||  Logical OR e.g.    (a==b)||(c!=d)
 !  Logical NOT e.g.  (!(a==b))        (equivalent to (a!=b))

Note: These operators are needed in both JavaScript and Java so you should be very familiar with these.


There are several different types of loop in JavaScript:  while, for, do...while and  We will look at the more common of these - while and do.  


This one will loop forever until the condition for the loop is met.  Naturally, care must be taken with while loops or code can end up in an infinite loop.  The following code will loop 5 times and give 5 alert boxes showing the value from 0 - 4. 
var x = 0;
while (x<5) {
    alert("x = " + x);
    x++;      // this increments x by 1
If the coder were to forget to add the line 'x++', this would result in an infinite loop.


Slightly more complicated, the for loop has the following format:
for (initialization; conditions; change) {
Taking the same previous example again, we could achieve the same effect with the following:
for (var x = 0; x < 5; x++) {
    alert("x = " + x);
Which looping approach you wish to use is entirely up to you, as long as it gets the job done.

 A JavaScript Form Validation Example

So let us take a few of the concepts we have previously introduced and use it to create a more complex example.  Tthe following example shows how JavaScript can be used in a simple way to enhance a web form:

  <title>Simple Example JavaScript Form</title>

  <script type="text/javascript">
  function testNumber() {
    if (document.ourform.number.value < 1) {
alert("Too low!  1 is the lowest number you can enter!");
document.ourform.number.value = 1;
return false;
else if (document.ourform.number.value > 10) {
alert("Too high!  10 is the highest number you can enter!");
document.ourform.number.value = 10;
return false;
else return true;

  <form method="POST" onsubmit="return testNumber()"
    action="javascript:alert('The form is submitted.')" 
  <br/>Because this is just a simple example, this script doesn't test the 
  situation where the user enters letters instead of numbers. Here you should just 
  experiment with numbers, negative, positive and non whole, inside or 
  outside the range.
  <br/>Please enter a number between 1 and 10:
  <input name="number">
  <br/><br/> <input type="submit" value="Submit"> 
  <input type="reset" value="Reset To Default Values"> 
Source and Output: javascript_validation_example.html

Note: The action attribute for the form has been set to simply return a message box indicating that the web form had been submitted to the server.  As we have not yet completed any server-side code, this makes sense to do now in this example.  In reality, this would point at a URL of the web application which has been developed to handle our form data.

As can be seen, the onsubmit attribute on this form calls the JavaScript method in advance of the form being submitted.  If this method returns false it will not be submitted.  However, if it returns true then the form submission would take place.  As stated in the code, this only provides some basic validation but it should give an indication of how validation is handled with JavaScript.  In reality, most development frameworks and JavaScript libraries have built in validation libraries which are better to use than developing your own validation.  There's no point in reinventing the wheel!

The object-based concept can be seen in the reference to document.ourform.number.value - the form (ourform) is the parent of the input field (number), which in turn is the parent of it's value attribute (which will contain whatever is entered by the user). Likewise, the form is a child of the document, which in turn is the child of the window (ie. our browser). 

What do I need to know?

In some previous years, JavaScript was not examined as there was less emphasis placed on it in the module (after all, the module was called Server-side Development).  As mentioned before, modern development has been becoming more JavaScript focused recently.  Combined with the fact that I would like more emphasis being put on "hands-on" skills (rather than learning off by heart) I am now expecting students to be able to write JavaScript code in examinations.  I will be expecting students to be able to write JavaScript code, using each of the features described above to perform some relatively simple functionality.  Following are some indicative questions of the type of things which could be asked in an exam (note: these will not be the questions, but understanding them and practicing them will help towards any questions I might ask.  Asking these questions would just facilitate JavaScript by memory).

JavaScript Challenges

  1. Create a HTML page which is simply a string 2_4_6_8_10_12_14_16_........_3998_4000    (Do this with JavaScript - no points for typing it out!)
  2. Build a calculator has two text inputs and three buttons ( + - and *).  Users should be able to type numbers into both boxes and the corresponding button will result in an alert for the sum, subtraction or multiplication of the two values.
  3. Write some JavaScript code demonstrating the use of 'onsubmit', 'onchange' and 'onfocus' events.
  4. Taking the example javascript_validation_example.html above.  Modify it so that instead of an alert box being used to indicate an invalid form, some red text appears to the right of the number box in either of the invalid situations.


According to the website

"jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development. jQuery is designed to change the way that you write JavaScript."

As mentioned previously in the discussion on the "browser wars", JavaScript has had varying DOM and CSS implementations across different browsers. In addition, the event management interfaces used to differ in JavaScript for different browsers. jQuery addresses this by providing a common browser API with simpler but more robust JavaScript code.  jQuery is tested and will run correctly on all of the modern browsers and has been growing in usage over the past number of years.

In addition, there are numerous plug-ins available for jQuery as well as some core additional libraries.  One of these core libraries is jQuery-UI which can be used to create impressive front ends for web sites, while maintaining browser compatibility.  

Let us take the "Hello World" type example for jQuery:

<title>JQuery UI Example</title>
<script src=""></script>
<script type="text/javascript"> 
     alert("Page has loaded and is ready!"); 

This is the body!
Source and Output: jquery_example.html

We have included the jQuery library remotely from Google's CDN (Content Delivery Network).  This saves us some hassle in getting this example to work and the CDN network speed far exceeds anything we could achieve locally.  

jQuery is designed to read and manipulate the document object model (DOM), so we need to make sure that we start adding events and widgets as soon as the DOM is ready.  To do this, we register a ready event for the document:

$(document).ready(function() {  ...... });

The code inside this ready event is called after the page has loaded in it's complete form.  

However, this really isn't impressive in itself, as we could achieve something similar through <body onload="someFunctionWhichDoesAnAlert()">.  The reason we are introducing jQuery is to show how we can implement new features, quickly and easily while having them already browser independent.  Let's combine this with jQuery-UI, one of the core plugins of jQuery.

To get jQuery-UI you can first choose a theme from and then download it from :   

<title>JQuery UI Example</title>
<script src=""></script>
<link type="text/css" href="css/humanity/jquery-ui-1.8.9.custom.css" rel="stylesheet" />
<script type="text/javascript" src="js/jquery-ui-1.8.9.custom.min.js"></script>

<script type="text/javascript"> 
    alert("Before we modify the DOM!"); 
$( "#button1" ).button();
$( "#button1" ).click(function() { alert("Winner!"); });
$( "#button2" ).button();
$( "#button2" ).click(function() { alert("No I'm the winner!"); });
alert("After we modify the DOM!");

<h1>Jquery-UI Example</h1>
<p>Below we will demonstrate some tabs...</p>
<div id="tabs">
<li><a href="#tabs-1">Home</a></li>
<li><a href="#tabs-2">Search</a></li>
<li><a href="#tabs-3">Admin</a></li>

<div id="tabs-1">This could be the homepage for an application</div>
<div id="tabs-2">Search page</div>
<div id="tabs-3">Some sort of administration page</div>

<p>And some buttons</p>
<button id="button1">Click me!</button> 
<button id="button2">No Click me!</button>
Source and Output: jquery_ui_example.html     (Note: To start modifying your own version you must download the .css and .js files for jquery-ui linked above.  You also need to preserve the indicated paths)

When the page is loaded, you will notice that on the first alert, the HTML page looks plain and normal, just like it would if we included no JavaScript and were not using jQuery UI.  Following this, the widgets (buttons and tabs) are added by jQuery and the page takes a proper stylized form.  By the second alert box, the DOM for the page has now been modified by jQuery and the page is ready for use with a fancy looking interface.  You can also see, from the code, how we have bound a click event to either button.  While in this example we simply displayed an alert, we could perform any task here we wished.

Note: the following example screenshot shows the above example using the "humanity" theme, one of the options available when downloading jQuery-UI.

Figure 3.2: JQuery-UI Example

You can find a more detailed set of available widgets and much more information at the following link:
Additionally, a second jQuery-UI example can be downloaded (and editted) from:  jquery_ui_example2.html     (this is the one which downloads with jQuery-UI)


There are a number of transitions and animation effects which can be added to jQuery-UI components  (or any DOM components on a website).  These include showing, hiding, sliding, fading etc. The following example is identical to jquery_ui_example.html except that we add some animation on the tabs.  Consider how difficult it would be to try to code this oneself in JavaScript.  In no more than a few lines we have a tab system complete with animation.

fx: { height: 'toggle', duration: 'slow' }

Below is another example of jQuery animation in action.  This shows some custom animation I put together for an application involving the assignment and removal of "Roles" from "Users" in a system.  While a smaller snippet of the overall page structure, we can see from the example how we can customise animation.  On clicking a role, a number of things happen:
  • The role moves either left or right in a smooth animation
  • The role box changes colour
  • The + icon changes to a - icon or vice versa
While this example is considerably more complex, you are welcome to look at the code to see if it makes sense to you. It is complicated so don't be disheartened if it doesn't make sense to you.   You would not be expected to produce anything like this in a closed book exam scenario (nor would I be able!).  It is simply provided as an example of how we can use jQuery for advanced animations.  In my real-world application of this code, it also calls an Ajax method to modify the database, adding or removing the appropriate roles before the animation occurs.  If the database operation is not successful (failure or lack of authority to assign a role for example) then the animation does not occur.  

What do I need to know?

While you are expected to write JavaScript scripts, you will not be asked to write jQuery code by heart.  You should be able to recognise and explain what is occurring in a jQuery JavaScript file.  You should be familiar with jQuery and jQuery-UI and their corresponding uses.  You should also be able to explain the steps involved in the creation of a HTML page which uses jQuery and jQuery-UI.

Can I use this for my assignment later?

If you are confident with HTML and JavaScript you may use jQuery if you wish.  It is not recommended for individuals newer to HTML and JavaScript as in this situation it is better to approach things in a simpler manner.  In general, the assignment does not have huge client-side UI requirements and plain HTML/CSS/Forms tends to suffice.   Having said all that, the very highest marks for the assignment go for impressive applications, which includes UI and system design (whether jQuery or not).