Scripting & JavaScript

I can't hope to provide and full and detailed JavaScript tutorial here - there are plenty to good books about, and I can't be bothered to write another one. I will therefore describe the basic concepts and give some examples of some of the sorts of things that are possible (i.e. on the other nine pages). If you're interested, you can then get yourself a book, or copy and paste some bits of my code until you get an idea of how it works.

There are also bits of JavaScript throughout this site to help position items on the screen according to your screen resolution, and to change the buttons on the left of the screen.

What is Scripting?

Scripting is the name given to a method of inserting little bits of "program" into a web page to make it more active. Web pages written in HTML alone (or using a tool such as Dreamweaver, Expression Web, or even Word) can be made to look attractive by using style sheets, etc., but they are still essentially static - i.e. they don't change. You can insert animated picture files, such as AVIs and GIFs, and created scrolling text using the <marquee> tag (beware - this is a non-standard HTML tag and is frowed-upon in web-design circles) but you can't make pages interact with the user.

The use of scripts allows you to add some processing or interactivity to your page. This can either be done on the web server before the page is sent to the viewer (called server-side scripting), or in the browser on the viewer's computer.

Server-Side Scripting

When you're looking at a web page, you're essentially connected to a network, and fetching files from the server that holds the pages. If you want to personalise or activate your page, the first possibility is to run your program on the server, as the page is actually created.

Many ISPs no longer offer web-space as part of their basic packages, and if they do, then you probably aren't allowed to run server-side scripts - for reasons of security and processing load. It therefore tends to be large companies, which host their own pages, that use this method. There are, though, many low costs hosts - and even one or two ones - that will allow you to host web-page and run scripts on the server.

Running scripts (and therefore processing the data) on the server can be more secure, and also quicker for the client, because all the data is kept on the server, and only the data that the client requires, or is authorised to see, gets sent across the (usually quite slow) communications link.

The way it works is that when you request a page that requires some processing (such as your Account Details page from a utility company web-site), the script is executed on the server. The server then generates what appears to be a plain HTML page, containing the results you wanted (e.g. your bill) and sends it to your browser. This also means that server-side scripting works well with older browsers, or lower-powered devices such as mobile phones, as they don't have to run any scripts themselves.

Examples of common server-side scripting lanaguages are Perl, PHP and Microsoft's ASP (Active Server Pages) or ASP.NET. You can try these for yourself on your PC by installing IIS (Internet Information Server, which comes with Windows from NT or 2000 onwards) or an open-source web server such as Apache.

My ISP and host (PlusNet) runs Linux servers that use Apache, so server-side scripts for Advanced ICT in a Nutshell are written in PHP.

For more information on PHP, ASP, etc., look at the server-side scripting page.

Client-Side Scripting

As some ISPs won't let you run server-side scripts, most of us have to make do with client-side scripting. Your browser is effectively the client, and it is your browser that interprets (or executes) the client-side scripts.

JavaScript is the most common scripting language - it is supported by all the main browsers, including Internet Explorer, Opera, Firefox, Chrome and Safari. The alternative, VBScript (a variant of Visual BASIC), can do similar sorts of things, but will only work in Internet Explorer.

Scripts written in JavaScript are delimited using the <script language="Javascript"> HTML tag, and can exist as text inside your web-page. They can take input from the user, pop-up dialogue boxes, write text to the page itself, redirect users to other pages, perform calculations, and, probably most usefully, change the properties of objects (such as pictures) on the page. From JavaScript 1.1, this means that you can write scripts to animate pages yourself by swapping the source of images after they have been displayed. Most of the examples here use that technique.

For anyone who has programmed using either C or C++, JavaScript will look quite familiar, except that it isn't typed. Looping and function declarations are similar, but there are no char, int, etc., type variables. This can lead to some interesting effects, as if a = 1 and b = 2, then a + b will sometimes uses arithmetic addition to give you 3 and sometimes use string concatenation to give you 12 (depending on the time of day and wind direction, apparently!).

Which is Best?

There isn't always one solution that's always best - it depends on what your web-page does. Server-side scripting is better for web-pages that require you to log-in, or present different information for different users. Server-side scripting is also the best option if you want your page to read and/or write data from/to a file or a database. Client-side scripting is used for things where speed is important - such as animating "roll-overs" or validating user input - and you don't want to wait for your data to be sent to the server and then wait for the response to load. Client-side scripting can change a page without re-loading it, whereas running a server-side script requires the user to either refresh the page or move to a new page.

There's nothing to stop you using both, of course - you could, for example, use JavaScript to validate some fields on a web-form have been completed correctly before using server-side scripting to save the data into a database, or you could use server-side scripting to select timetable details from a database and then draw the timetable on the client-side, e.g. using Canvas.

The examples on these pages mostly interact with the user in a real-time fashion, and therefore the scripting is done on the client side. There is more information on the server-side scripting page.

Cookies

For some reason, people get a bit scared when you mention cookies. A cookie is just a small file (or part of a file, depending on which browser you're using) that can be used to store information on your computer, just like a variable. By default, they only have a lifetime of the browser session (i.e. they are deleted when you close your browser), but you can set an expiry date if you want them to persist between sessions.

They are useful because JavaScript variables are destroyed when you leave the page - cookies can therefore be used to pass values between different pages. My personal site makes use of a cookie to remember the names of people who come to visit, and to count the number of visits they have made. It is also used to help display the pictures as all photos are displayed by the same page. When you click on a thumbnail, the name of the picture you want to look at is written to the cookie, and you are redirected to the picture_viewer.html page. That looks in the cookie for the filename, and then displays the picture. Much easier than having a separate page for each picture!

About The Scripts on These Pages

There is a number of scripts in these pages. The basic principles behind how these scripts work is described below - to see the script in detail, go to the relevant page and View Source.

Lottery

This is a very simple script that generates sequences of lottery numbers. In fact, the whole thing is done twice, once in JavaScript and once in VBScript, to show that you can happily mix the two on a page.

Picking random numbers to generate the balls is fairly straightforward in most programming languages - although, strictly-speaking, we should call them pseudo-random numbers because they are generated using an algorithm. The problem is that the balls aren't replaced, so we need to check that each number only comes out one. Each new number generated is compared with the previous numbers drawn to ensure that it is unique - in fact, the numbers are repeatedly drawn until they are unique, although in practice this isn't normally more than once or twice.

The balls are <div>s with rounded corners (the border-radius style that rounds the corners isn't supported by older browsers, so they may appear as rectangles on some computers). The .innerHTML property of a <div> contains its contents, and can therefore be used to set the number of the ball. Finally, the background colour of the <div> is changed so that the ball colours match those in the National Lottery (although the white one is grey so you can see it against the white background). The colours are stored in an array - the value of the ball is divided by 10 and rounded down to be used as the array index, e.g. 23 → 2.3 → 2 gives colour[2].

Click here to view the lottery page.

Body Mass Index

It was in the news one day that more than 50% of Americans are now obese according to the WHO guidelines. This is a very simple page that takes the two numbers you've entered, performs the calculation, and sticks the result in the third field.

Click here to view the body mass index page.

Coins

I was teaching probability one day, and was trying to explain that just because the probability of tossing a head or a tail is 0.5, it doesn't necessarily follow that if you toss ten coins, you'll get 5 of each. Tossing 10 real coins would involve a lot of noise and having to record the results, so I created this page.

When the button is clicked, it generates an array of 10 random numbers. The numbers are between 0 and 1, and so when rounded will give you either 0 or 1. The code then loops through the ten images, and if the corresponding random number is 1, it changes the picture to one of a head, otherwise it displays a tail. It keeps a count of how many heads there have been, and displays the number at the bottom of the screen. The number of tails is calculated by subtracting the number of heads from 10.

Click here to view the coin page.

Cards

Well, this is a trick, as you may have guessed. There are actually 11 cards that are displayed - the original six, and then another five, and the blank one which appear when you click the button, so all of the cards actually disappear.

The script just rotates the image sources a random number of times, so it looks like the cards are being shuffled. Then when you click the button, it changes the image sources for the new 5 cards and the blank one, and shuffles them again.

Click here to view the cards page.

Dice

Back to Maths again... During my PGCE, some of the people on my course were trying to produce an Excel spreadsheet to do this. They wanted to simulate the throwing of two dice, and then plot a graph of the results to produce what would hopefully be a normal distribution curve (provided the sample size is big enough).

The web page models exactly what you'd do yourself. It generates two random numbers from one to six, adds them together, and tallies the results. To produce the graph, it then changes the width property of the coloured bars, which are in fact just GIF files containing a single pixel (see the Images section in HTML for more details/examples).

Click here to view the dice page.

Game Show

Yet another mathematical problem! This one was described in Ian Stewart's Christmas Lecture on BBC2, but was originally described by American mathematician in a newspaper column. The gist of it is this: you're on a game show, and there are three doors, behind one of which is a prize. Des O'Connor (sorry, I mean the host) asks you to pick a door. He then opens another door to reveal that the prize is not behind that one. He then allows you to change your mind before opening the door to see whether you've won. What should you do?

Well, it appears that you're twice as likely to win if you change your mind. The probability of the prize being behind the first door you choose is 1/3 - fair enough. But that means that the probability of it being another door is 2/3. The host has opened the other door, but the odds don't change because he knows where it is. That means that there is a 2/3 probability that the prize is behind the other door!

That sounds fine in theory, but, ever the sceptic, I decided to create this simulation to test the theory. Again, it uses pseudo-random number generation to pick one of the three doors, and then lets the user pick one. A non-winning door is opened (i.e. the image is swapped to the cross), and you can then change your mind. There are no new techniques used here - it's just a diferent application.

Click here to view the game show page.

Words of Wisdom

This was a rather surreal attempt to use a random sentence generator to explain the difference between validation and verification (i.e. it can produce a valid sentence that isn't true), but it turned out to be a little too abstract for the students. Still, it amuses us!

It takes two arrays - one of noun clauses and one of verb clauses. It then picks, Carol Vorderman-style, using pseudorandom numbers, two noun clauses and joins them together with a verb clause to produce a sentence.

The page uses three frames (one with the title in it, the one where the sentence appears, and the one at the bottom with the button on it, and demonstrates that you can use scripts in one frame or page to write to another.

Click here to view the words of wisdom page.

Puzzle

I've just included this one to show off, really! I wrote the script when I was bored one afternoon in the summer holiday, and was rather shocked when I discovered that it actually worked. Again, it uses random number generation to jumble the squares, and then swaps the source of the images to make it appear as though they are moving around. The gap is a transparent GIF file.

Click here to view the puzzle page.

Enigma

Well, when I'm not listening to Kraftwerk and doing integral calculus for the fun of it, I'm quite interested in cryptography. This page uses an image map for the keyboard, and the image-swapping technique to make the bulbs appear to light. It's really quite simple - the rotor wirings are represented by arrays of numbers which are the corresponding positions on the next rotor, and the reflector works in the same way. Now go and make a Lorenz machine for your homework!

Click here to view the Enigma page.