ICT Learning Centre
Javascript - writing an event driven page
Written by James Murphy on 2009-11-02
 

So I guess it's about time that we had a look at javascript. Javascript is the client-side scripting language supported by all the browsers. While client-side scripting can be written in other languages (vbscript, c, tcl etc.) the vast majority of client-side scripting is written in javascript. So first question: what is meant by client-side scripting?

Client-side scripting is that set of scripts that runs on the clients computer (rather than on the web server). For security reasons, most client-side scripting languages are designed to be unable to write to files and can only interact with the clients file system on a very rudimentary basis (generally only able to read from cookies and .js files). However, as they run on the local machine, they generally are not hit with any major request-response lag time and so are generally much faster than server-side script. So next question: what do we use them for?

Client-side scripts are used to improve the usability of a page, to make it more responsive to the user, to make it react more like a program than a webpage. Generally, we will use javascript for such things are prompts and message boxes (to warn people of things they need to know), form validation (to make sure that the information they are sending to the server is of the correct type and format) and for simple interactions (simple games for example). So how do we do this?

Javascript, generally, activates based on a trigger known as an event. Some examples of events are:

  • onLoad - when the page/element finishes loading
  • onunLoad - when the page is being left (when we are moving to another page)
  • onClick - when an element is left-clicked on
  • onDblClick - when an element is double clicked on
  • onkeyPress - when a keyboard key is pressed (in relation to a particular element)
  • etc.

There are many more. For a full listing check out http://www.w3schools.com/js/. In the element we wish to interact with we simply add an attribute whose name is the name of the event we are interested in. Let's take an example to demonstrate what I am talking about. In the next blog you will find code for a simple tic-tac-toe game written using javascript.