As with the other similar pages on this site, this page is designed to be easily printed out and read offline, away from the computer. If you are trying to follow this lesson online you will find it much more convenient to return to the full lesson 8 menu.
SPECIAL NOTE ABOUT THIS PAGE: This lesson deals with techniques which make changes on the screen. It is obviously impossible to reflect these on the printed page. You may still find this "printer-friendly" version of the lesson useful, particularly as a record of various JavaScript events and related objects, but on the whole I suggest you would benefit more from following the whole lesson through online.
Contents
We've already seen a few examples of the use of JavaScript events to cause changes on your web pages; rollover images, for instance. We will also go on to see more (buttons as links, opening new windows...). It's time to clarify exactly what this technique is, discuss some things about events and how they work, and provide a list of all available "onX..." events. A discussion of what JavaScript actually is can be found in the next section (8.2), about the <SCRIPT> tag.
One application of these which hasn't yet appeared on this site is that of alerts. I'll mention these now, as they provide a useful illustration of the technicalities involved, and also of the distinction between the two most common events, onClick and onMouseOver (and its complement, onMouseOut). This is an occasion when you should look at the online version of this page (http://www.leeds.ac.uk/acom/html/subj_onclick.cfm) to see these in action.
This is very easy to do in JavaScript - the following code is all you need. The first is for an (irritating!) onMouseOver alert; the second a (useful!) onClick alert.
<a href = "#"
onMouseOver="alert('This is where your text goes');return true;">
the link text goes here
</a>
<FORM ACTION="">
<input type="button" value="Click on Me!"
onClick="alert('This is not so irritating, and could conceivably
be useful'); return true">
</form>
onClick and onMouseover are the "events". There are other event handlers you can use, which will have predictable effects - for example, onFocus changes what happens when a user 'focuses' on an object: you can focus on something by clicking on it or by 'tabbing' (pressing the Tab key to cycle through options) on to it. You can cycle through links with the Tab key, for instance: or form buttons. The table below details the common event handlers in JavaScript:
| Event | Event Handler |
|---|---|
| Moving the mouse over something | onMouseOver |
| Moving the mouse off something | onMouseOut |
| Clicking on something | onClick |
| Changing a form element | onChange |
| Clicking on a form element | onFocus |
| Clicking on a different form element (e.g., you have focussed on something and are now changing your focus to a different part of the page) | onBlur |
| Loading a page | onLoad |
| Selecting a form element (again, pretty much the same as onClick or onFocus) | onSelect |
| Submitting a form | onSubmit |
| Moving away from a page | onUnload |
An event provokes an object (a rather confusing term in this case: not only is it not an "object" in the usual sense of the word, it's not even an "object" in the web design sense; that is, an image, horizontal rule, or anything like that). Without a complete understanding of JavaScript, the best thing to do is simply take note of the exact syntax of these objects, and re-use them in your own particular context when necessary; it is usually obvious which bits of the code you will need to replace. The alerts shown above were one object, and obviously it's the text within the brackets following "alert" that has to be changed. (Technically that's known as the object's argument; again a strange use of a word. An argument in the programming sense refers to a value taken by a function.)
Here's another object, from lesson 7.5 on rollover images:
<A HREF="#" onMouseOver="document.baby.src='madbaby2.jpg';"
onMouseOut="document.baby.src='madbaby.jpg';">
<IMG SRC="madbaby.jpg" name="baby"
border="0" ALT="Rollover image demo">
</A>
As detailed on that page, here the variables are the images involved, and the NAME given to the image. Note, incidentally - and this is important - that although on several occasions I've shown you code including an event/object across two lines of the screen in order to avoid formatting problems, you should always ensure an event/object is typed in a continuous line of text. The most obvious example of this problem comes in the lesson about opening new windows (lesson 10). It doesn't matter if in Notepad the line appears to "wrap"; just don't type a carriage return or any extraneous spaces in the line, and let the text editor break the line itself.
Still another object occurred at both the top and bottom of http://www.leeds.ac.uk/acom/html/ext_orwell.cfm - the text of "Politics and the English Language" - when clicking on the link closes the window. The link looked like this:
<A HREF="#" onClick='window.close()'>Close
this window</A>
Don't forget the empty brackets. Use of the onUnload event, by the way, is the method through which some web pages irritatingly bring up further windows when you're trying to move away from their page. It's a phenomenally annoying tactic and in my opinion counter-productive as anyone trying to do that is bugging people so much they will lose business, not gain it!
The onChange event was used on the form-based menu in lesson 10. You could conceivably use this and other form-related events to bring up "captions" to form elements as the user moves around the form; another example of creative use of combinations of techniques. For even more fun and frolics with this kind of thing (my, we're full of it today), see http://www.leeds.ac.uk/acom/html/ext_backcol.cfm.
Finally, you might want to alter the information shown in the status bar, at the bottom of the screen. The default state is to show there the URL of the destination page when the mouse is over a link. But this is not always satisfactory, particularly if the URL is obscure. You can do this as follows:
<A HREF="index_az.cfm"
onMouseOver="window.status='Return to the menu for lesson 8 (JavaScript)';
onMouseOut="window.status=' ';
return true;">Back to the menu for lesson 8</A>
All these events (with some imagination and thought about how to combine them with other techniques) can considerably add to both the style and the user-friendliness of your page. But as with everything else, don't use them gratuitously, especially alerts.
JavaScript events are just the start. They are not actually attributes, but they have the appearance of them, being neatly containable within individual tags. In fact what these actually are, are references to JavaScript functions that the browser can pick up and activate in certain circumstances. But in the examples shown on the events page, the objects being called up were pre-defined. In other words, it was possible to give the browser all necessary information from within the event handler (or more generally, from within the tag). Don't underestimate the power of this though - at this point you should look at http://www.leeds.ac.uk/acom/html/subj_script_tag.cfm to see this working calculator, although I've included it on here to give you a visual impression. This was rendered entirely by JS events.
That's not my own work I hasten to add! I'll tell you where you can find ready-made JavaScript creations like this below in 8.2.2.
With more complex functions, it will not always be the case that you can contain everything in the tags/events. You may need to define the function in the document header, and then refer back to it in the body. Or, you may have several identical events in your document and want to save some time by only defining the event once, but calling it from several different places (an example of that comes in 8.3 below). This is where the <SCRIPT> tag comes in.
Again it is useful to refer back to a previous page - lesson 7.7 to be exact, about preloading images. Recall that there, the code necessary to conduct the image changing was split, between the body of the page and the header. When you need to put code in the header like this you need to enclose it in <SCRIPT> tags, like so:
<script type="text/javascript">
<!--
no1 = new Image(379, 412);
no1.src = "jupiter.jpg";
no2 = new Image(379, 412);
no2.src = "jupiterpainted.jpg";
function changeimage (imgTagName,imgObj)
{
if (document.images)
{
document.images[imgTagName].src = imgObj.src
}
}
// -->
</script>
The TYPE attribute is obligatory, and should (with the applications you'll be using this for) always take the value as shown. Do note that you will often see LANGUAGE="JavaScript" used instead of this, and while this works perfectly well it is not part of the HTML 4.0 standard, and will therefore not validate. TYPE will, however.
The only other things to really draw attention to at the moment are the comment tags which lie inside the <SCRIPT> tag. Some older browsers cannot handle JavaScript, but by commenting out the contents of the tag (but not the tag itself, note), this potential problem is removed. Note that the comments should be on separate lines as shown in the code above.
For some information about the sort of stuff you get within the <SCRIPT> tag, and how to call it from within the document body, see section 8.3.
Although you might be thinking JavaScript is way too complicated for you to start incorporating into your pages, there is a cop-out solution (and one which I use all the time myself...). Many sites act as sort of 'script-libraries', and feature scripts that anyone can use in their page as long as they include a link referring back to the original site. The calculator you saw above was from the JavaScript source at http://javascript.internet.com/ and is an example of the much more elaborate things you can do with JavaScript if you know how.
To get scripts like this into your page all you need to do is to copy and paste the relevant bit of source code into the body of your HTML file. JavaScript source code libraries have thousands of different scripts you can copy into your own page with a minimum of effort - most of these libraries ask you to do just one thing, which is to include a link back to them (some say that you should not alter the code at all either - you will find instructions usually in the same place as you find the code).
However, although copying sections of other people's code into your own HTML is a good way to introduce JavaScript into your pages, you are obviously limited in what you can achieve as you can only do things that have been done before, and certain more personalised effects will be unavailable to you unless you are able to modify existing scripts or create your own from scratch.
There's one other word of warning. Upon finding all these marvellous, ready-made scripts just waiting to be harvested, some users get over-excited and start cramming their pages with dreadful gimmicks. Here are some of the worst offenders - scripts that:
There are many more examples of excess. The very titles of some of the available scripts from the JavaScript Source make me cringe: "Flashy Fading Rollover Menu"? Please! Also, adding in code like this can cause a page to fail to validate. It can also throw out a well-crafted, stylish site: it's like, you've spent ages putting together a meal full of your own personal touches and style, and suddenly for pudding you serve up the packet cheesecake. Only use scripts which fit your site, in other words.
But having said all that there are a lot of interesting and useful things on there - remember, however, that they gain their power through selective and discerning use, not constant exposure. And, unfortunately, past experience with the inclusion of ready-made scripts forces me now to include the following disclaimer: It is not the responsibility of myself or the ACOM demonstrators to try and work out what is going wrong with a script you've copied in from somewhere else. Sorry! But don't let all that put you off looking around for ready-made scripts. They're another technique, that's all - one that like every other technique can be used well, or used badly.
JavaScript takes us beyond just the marking-up of text and into the realms of proper programming. JavaScript is a simplified version of the full programming language, Java, a language with certain security features which made it ideal for use on the Web (and which I'm not going to get into). But to describe fully even the simplification that is JavaScript is beyond the scope of this option. But we can make a start, and for those who feel inspired to learn more, some links are provided below. /P>
If you do a web search on JavaScript you are bound to come up with hundreds of other examples, so do not stop at these.
In JavaScript a few commands are written in a sort of short-hand, and an understanding of what these characters represent will be useful. The { opening curly bracket symbol means "begin" in JavaScript, and the } closing curly bracket means "end". As with most programming languages, sets of instructions which are to be carried out together start with a "begin" and finish with an "end" - in the case of JavaScript, they start with a { and finish with a }. If you have a number of statements making up a command (do this then that then the other) each statement is separated from the other statements by a semicolon. All JavaScript programs start with a <SCRIPT> tag and finish with a </SCRIPT> tag. The JavaScript program usually goes in the head of the document as that is the part of the HTML file which is read first - this ensures that the scripts for a page are all loaded before the page content is displayed (so if the scripts affect the content there won't be a problem).
To see what this all means in practice, let's start with a simple example; although really you need to see this online (http://www.leeds.ac.uk/acom/html/subj_jsfunc.cfm). I'll explain the coding here though.
This is an alert that responds "Hello ______!" where the blank is filled by whatever was typed into the text box. It uses an onClick event built into the form button, and here's the HTML that produced it:
<FORM ACTION="">
<INPUT NAME="Textbox" TYPE=Text>
<INPUT NAME="submit" TYPE=Button VALUE="What's your name?"
onClick="yourname(form.Textbox.value)">
</FORM>
But we can't use an ordinary alert, because of the variability of the text, depending on what name (or any other text) the user types. Somehow, the contents of that form box must be passed to the alert - and, incidentally, have other text added to it (the "Hello... !" bits). What the onClick event in this case actually contains is a call to a function defined in the document header. This function is called yourname, and it is defined (between <SCRIPT> tags) in the header as follows:
function yourname(whatname) { alert ("Hello, "+whatname+"!") }
Let us take apart this line of code bit by bit.
Remember that whatname will "pick up" the value passed to it when the function is called in the onClick event. So it's the contents of the brackets after yourname which are the final part of this function:
I know all this sounds complicated - and it is, compared to HTML - but hopefully, if you look at all this carefully, you can see how it fits together. Things might be clarified by the following example as well. This calls the same function (yourname), but from a different context (still an onClick event, but in a link, not a button) and with a different argument: the code follows the link. Note now that the argument is not a variable, but a fixed quantity; the string of characters "World". Fixed quantities are identified as such as they appear in quotation marks, but note the need for single quotes. Had I enclosed 'World' in double quotes the browser would have become confused and assumed the function had ended after the opening bracket.
<A HREF="#here" onClick="yourname('World')">Hello World!</A>
What we've done here, then, is call the same function from two different locations on the page, and pass a different argument to the function in each case. The function there was very simple, but some are more complex. In that case, it would be quite a time-saver to only have to type a repeated, complex function once, rather than placing it in tags each time, in full.
Here's an adaptation of some links from the lesson where we used JavaScript to open a variety of new windows: once again, though, you should look at the online version (http://www.leeds.ac.uk/acom/html/subj_jsfurther.cfm).
When this technique was previously used, we had long onClick events in each link. But now there is just an HREF attribute. However, the links do not call up new HTML files, but instead, call a JavaScript function defined in the document header. The links each look like this - with the name of the HTML file different each time, according to which flag they surround:
<A HREF="javascript:newWin('argentina.cfm');">
Remember the elements of JavaScript. The link now says to the browser, "call a function with the details that follow the colon. Actually, you've seen this sort of thing before, in mail-to links, where the browser opens a mail application rather than trying to download another file, and passes to that application whatever follows the colon: in that case, an e-mail address. Here, it passes the function name and argument. The function newWin, as in previous examples, is defined in the document header:
function newWin(URL)
{
aWindow=window.open(URL,"countrywin","toolbar=no,width=500,
height=500,status=no,scrollbars=yes,
resize=yes,menubar=no");
}
(IMPORTANT: note this is a case where the text above should be run together without spaces or line breaks. I have had to introduce line breaks here to fit it on the page, but the actual code does not contain them.)
The object in this case is window.open. That takes three variables, though the third is very long and itself subdivided. The first variable is the URL that the new window contains. This is a "genuine" variable; in other words, it can take different values depending on what is passed to it in the document body. (You can tell it's like this because it doesn't have quotes around URL.) So, each time the function is called, we need to pass it this info: "argentina.cfm", "bolivia.cfm" and so on. The second variable is the name of the new window. (This could be left blank in this case but I have included one for clarity.) The third variable is the long string of information about what the window should look like.
In practice this makes little difference to the functionality of the page, but it is a more efficient use of code, and easier to put together. The best thing to do is look at the section on opening new windows (lesson 10) and compare the code of the two methods, to see which one you ultimately prefer.
Incidentally, before you use this technique on your site, please do have a good look at the section of lesson 10 on navigation and accessibility.
There have been several occurences of JavaScript on this site so far, and more will come. To repeat, there is simply not the time and space in this course to take things any further. Like many other advanced techniques, remember that JavaScript is just padding. Be wary of using it to pass on any important information that is not available by other means. As with image maps, always have a text alternative, and/or don't make the JavaScript absolutely integral to the page, just in case a reader can't view it for whatever reason.
If you want to go further with JavaScript then get yourself a decent manual. O'Reilly's series of manuals are always amongst the best available, and the relevant one is JavaScript in a Nutshell by David Flanagan. There is also the JavaScript Pocket Reference by the same author, but this is pretty expensive for what you get.
It might also be a good idea to learn some basic principles of programming - to get a better handle on what a function is, variables, arguments, and (if you are thinking of writing your own scripts) some processing terminology such as iteration. JavaScript syntax is modelled on Java syntax, which in turn is modelled on C++, so anyone who picks up these more complex languages should have no problem with JavaScript. In turn, JavaScript can serve as a useful primer for some true programming. You may, of course, choose to take (or already have taken) the relevant ACOM module here: ACOM1910: Programming IT Skills. This requires no foreknowledge of any programming, incidentally.
Note that more complex web page interactivity, of the sort you might see on e-commerce sites, may also be written in the languages Perl or (for online databases) SQL or its variants. Again, though we can't offer this level of tuition in this course, there are several manuals and start-up guides available. You should realise, however, that in order to make full use of these techniques you may need access to a server at a level that is not possible on the normal Leeds University student system. If you do become interested in programming web page functionality at this level, you will have to contact an Internet Service Provider and establish the means by which you can incorporate these kinds of techniques on your site.
Happy scripting!
End of lesson 8.
Material on this site is © Drew Whitworth and ACOM, 2002. Permission will usually be given to reproduce material from this site for non-commercial purposes, if credit is given. For enquiries, e-mail Drew at drew@comp.leeds.ac.uk.