| An Introduction to JavaScript | ||||||||||||||||||||||||
|
What is Scripting and why use it? HTML web pages can look great. Wonderful use of colours and layout, nice fonts and great graphics make for a lovely page that is a joy to behold. But they don't DO anything. They are static and the only time they change is when you change them. "So what's wrong with that?" I hear you ask. Well, supposing you wanted to welcome visitors to your web page, you could just have a line of text that said, 'Hello, Welcome to my Web Page' but wouldn't it be nicer if you could say 'Good morning/afternoon/evening' depending on the time of day they were visiting your site. Now your page would be dynamic. Two people viewing your page at exactly the same time but in different time zones could get two different welcome messages. For example in the UK they would see 'Good Afternoon' but if they were viewing the same page at the same time in US the time difference would mean that they would be welcomed with 'Good Morning'. That is a very simple example but it illustrates the usefulness of dynamic web page content. Some other uses of scripting would be for things such as validation of data entered by a user - make sure when you ask for an email address on a form, you really get an email address! Or dynamically changing images on an event (more about events shortly), this is commonly used on rollover buttons. The two main types of client-side scripting are JavaScript and VBScript. Client side simply means that your script runs on the browser of the visitor to your web page. Server side scripts run on the web server and deliver the results to the client browser. The format of JavaScript is very similar to C or C++ so if you have used either of these languages before you will have and advantage in adapting to JavaScript. But if you have never programmed anything more complicated than the VCR before, don't worry. I'm not going to try and teach you C programming or anything like that and believe me, that is a bigger relief for me than it is for you! We are going to learn by the use of some examples that literally anyone can use and then enhance for their own web pages. Using events to trigger scripts Examine the code below and the resultant web page. ![]() Figure 1.1 - Example JavaScript using onMouseOver event ![]() Figure 1.2 - The result of the code from Figure 1.1 As you can see from the above figures the JavaScript code (starting with the 'window.status' and ending with the 'return true') is triggered by the 'OnMouseOver' event. As you move your mouse over the A HREF link the JavaScript changes the text in the Status bar of your browser window. Figure 1.2 shows the code in action. So events are things that happen either due to some user action (moving the mouse cursor) or more general actions like loading a page. There are several 'events' that occur in many different elements of the page. Here are some of the common ones:
Time for another example. ![]() Figure 1.3 - Example using the onUnload event When you look at this code in the browser you will see the following: ![]() Figure 1.4 - The result of the code in Fig. 1.3 ![]() Figure 1.5 - Alert box appears when you close the document Now we know how to use events to trigger our JavaScript code. Using the SCRIPT tag Scripts start and end unsurprisingly within SCRIPT tags. Let's go back to the example that we first talked about in the opening paragraph. ![]() Figure 2.1 - Saying hello with finesse I first opened this page at 5.40pm and got the following. ![]() Figure 2.2 - The results from Fig. 2.1 opened at 5.40pm Then I opened the page again at 6.01pm - Gosh I'm slow, well actually no, I just moved the clock forward a little. Either way, I got this: ![]() Figure 2.3 - The results from Fig. 2.1 opened at 6.01pm Neat, huh?! Let's investigate how we achieved that. You will have noticed that I have included line numbers against the code in Figure 2.1. This will hopefully make things clearer as we dig a bit deeper. First of all we included the SCRIPT tag (line 4) and we also told the browser what language we were going to write our script in. As we said earlier, we could also be using VBScript. But in this case we are using JavaScript. After the SCRIPT tag the browser will now try and interpret everything until it reaches the closing SCRIPT tag (line 18) as JavaScript. Forgetting to close your SCRIPT tag will really confuse the browser and give you some outstanding error messages. One possible problem you might run into is that some older browsers such as Mosaic or Lynx can't handle scripting and consequently will try and display your script on the web page as if it were normal text. Not entirely helpful. So it is always good practice to use 'comment' tags which means that your script will be hidden to the older browsers that can't cope with it. Lines 5 and 17 open and close the comment tags respectively. They're also good for putting comments in your pages! In lines 6 and 7 we are creating variables. If you have done any programming before you will be familiar with variables, if not, you can simply think of variables as containers (like a bucket) with names on them. We are creating two variables called 'now' and 'hour'. The 'hour' variable (or bucket, labelled 'hour') is derived from our first variable. Line 6 basically says, "put the value of the computer's date and time into a variable called 'now'" and line 7 says "take the current hour from the first variable we created and put it in a container called 'hour'". So if 'now' was 02-Aug-2001 18:15 then 'hour' would be 18. Next we have three 'if' statements (lines 8, 11 and 14) to evaluate our variable. An 'if' statement is a simple process which can be translated as 'if this, then do that'. Really, it is that simple. In JavaScript it reads like this:
if ( this ) { do that }
What we are trying to find out with our 'if' statements is what time of day it is so we can show the appropriate greeting. So line 8 says "if the content of our variable is greater than or equal to zero and less than twelve run the code within the braces '{ }'". And remember we are talking about hours in 24 hour format here so this will determine whether it is morning. You may remember the greater than (>) and less than (<) signs from a maths lesson and the double ampersands (&&) mean 'and'. With that in mind, you should be able to see in lines 11 and 14 that we are also testing the current 'hour' to see if it is afternoon or evening. When one of our 'if' statements is true (the hour matches one of the three possibilities: Between 00:00 and 11:59, between 12:00 and 17:59, or between 18:00 and 23:59) the line of code following the 'if' statement is executed (Line 9, 12, or 15). The ability to write directly to a web page from JavaScript is very useful. To do this we use the function 'document.write()'. Everything between the double quotes is printed onto the web page. Now we have created our first 'proper' script using JavaScript. Although as you saw, the SCRIPT was all that was on the page. Now we need to think about how to integrate JavaScript into a web page that does more than just run a script. One way to do this is to use functions. Functional functions Functions are one of the main parts of JavaScript and almost any web page that utilises it will have one or more functions. You can think of functions as self-contained pieces of code that perform a process (function). The format of a function is:
When you write a function you declare it simply with the word 'function'. You then give your function a name; this is the name by which you will refer to your function when you want to call it. An argument (or parameter) is information that you can pass to your function, which it can then use as variables within the code. Finally, within the braces you have the actual code of your function. Don't worry if this all sounds a bit confusing at the moment. All will become clear. Hopefully. And so, on to an example of a function. ![]() Figure 3.1 - Example code using a JavaScript Function Ok, jumping straight in. You will see that we declare our function on line 5. It is called 'SayHello' and it has 1 argument or parameter called 'form'. In lines 12 to 18 we define a form on our page. The things to pay attention to are the input text box (line 14), which you can see, is called 'FirstName', and the Button we are creating called 'btnHello' (lines 15 to 17). Also note we are calling our function using the 'onClick' event trigger (line 17). Here is what we see when we view this page in our browser. ![]() Figure 3.2 - What we see in the browser using the code from Fig 3.1 So I type my name into the text box and click the button: ![]() Figure 3.3 - Click the Button! Clever stuff, huh! Right now there are just a couple more things to understand here. Line 17, as we said, calls our function when the button is pressed. What we need to look at now is the argument we are passing to our function. Whenever we need to refer to something in JavaScript we need to refer to it by name, sometimes called objects. You can see that our form has a name (line 12): 'Form1'. You will also notice that the input text box where I typed my name also has a name (line 14): 'FirstName'. The whole page has a name: 'document'. This name is fixed and each element on a page is child of the document. So to refer to the form I would say 'document.form1' and to refer to the input text box I would refer to that as 'document.form1.FirstName'. This is because 'form1' is a child of the whole document, and 'FirstName' which is within the form, is a child of it. So with this in mind, if you look back at when we called our function from the 'onclick' event on line 17, we could have called it by using:
SayHello(document.form1);
We actually used the 'this' object which is a way of referencing it simply and is a common shortcut. Rather like referring to yourself as 'I' rather than by your full name. Because we are calling our function from the button we created (which is within the form) we can say 'this' which refers to the button itself and 'form', which refers to the form, which contains the button. Now just as the form is an element of the document, the form's elements (the input text box and button) are properties of the form. This is why when we want to refer to the contents of one of those elements we need to reference it's value or contents. This is the reason for the 'value' element in line 7. Now if your head is spinning you've probably got it. This is one of the most difficult concepts for newcomers (and not so-newcomers) to scripting to understand. But it is also a very important concept as this really opens up the power and flexibility of JavaScript. So, let me take you through it one more time. Sorry folks, but you'll thank me later. Honest. In the example (figure 3.1) you've typed your name and pressed the button. When you click the button the event trigger passes the form, which can be referred to as 'this.form' from inside the button, to our function 'SayHello'. As we have seen, 'this.form' is another way of saying 'document.form1', the form's full name. Within the function the form can be referred to simply as 'form' since this is the name of the argument once it has been passed to the function. Now we can access the contents of the form's text input box called 'FirstName' by 'form.FirstName.value' which is exactly what we display in the 'alert' box in line 7. If you're still not clear please drop me an email to the address at the bottom of the page and I will be only too happy to help. And finally... No, that's it. That was an introduction to JavaScript. Yes, I know, we didn't but scratch the surface. But you have got to start somewhere. Hopefully, from this brief tutorial you will have been able to see the potential for incorporating JavaScript into your own web pages to make them more dynamic and exciting. |
||||||||||||||||||||||||