Web Design

Lesson 8: Printer-Friendly version

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.

You can also go straight to the printer-friendly version of lesson 9 from here.

NOTE for LESSON 8: Much of this lesson is concerned with techniques which cause things to happen on the screen, and it is obviously impossible to replicate that in printed form. In order to see these techniques in action, then, you will need to look at the online pages for this lesson. I have simply omitted those examples which can't be rendered in print and to save time and irritation, will not continually refer back to the online pages.

Contents

8.1 rollover images

Rollover images can change their state on screen. To make one, you need two images:

joe2.jpg joe2bw.jpg

This is an image called joe2.jpg

 

This is an image called joe2bw.jpg

The code below places joe2bw.jpg on the page in the normal way, using a standard <img> tag. What you must then do is tell the browser to swap the images over when a particular event happens. It is the idea of events, and how they are defined and used, which is the main topic of lecture 8 (as I hope the virtual lecture made clear). In this case, the event is known as an "onmouseover" event. If that doesn't make sense to you let's put a few spaces in - "on mouse over", or, "do something when the mouse is over something. This is a simple piece of JavaScript.

JavaScript events resemble attributes. They are placed inside tags in a similar way, with the same rules: they can appear in any order but always go after the tag name and never appear in the closing tag. There are only certain tags they can appear in, and <img> is not one of them, but that's OK - we can surround the image with an <a> tag and put the event in there, like so:

<a href="#" onmouseover="document.baby.src='joe2.jpg';" onmouseout="document.baby.src='joe2bw.jpg';">
  <img src="joe2.jpg" name="baby" alt="Rollover image demo" />
</a>

Because the image is not meant to serve as an actual link, the link is what is known as a dummy. The href="#" suggests it is an anchor link, but there is no destination. (Actually, href="#" does have a destination - it will return you to the top of any given page. If the rollover image is not an actual link but is not at the top of a page, you may need to define an anchor link at the image in question.)

As to the rest of that HTML, the key to the rollover technique is the name attribute. Just as in anchor tags and the <map> tag, by giving an HTML element a name, you are enabling the browser to refer to that element from another part of the HTML file. In this case, as it happens, the reference is made in the immediate proximity - i.e., the <a> tag immediately surrounding the named image - but it doesn't have to be, as I'll suggest below. Anyway, the onmouseover "attribute" consists of some JavaScript which basically says, "take the element named baby in the current document and change its src to the file joe2.jpg when the mouse is over that element." All rather logical, when you put it like that.

The onmouseout event changes things back once you're done. Note that there's nothing stopping you leaving the second image in place, by omitting the onmouseout portion; nor would there be anything stopping you loading up a third image when the mouse moves off, instead of reverting to the original.

The tag in which the onmouseover event is located doesn't have to be actually around the image being changed. It's the name which draws the two into a relationship, not their being nested. See this example. In the online materials you can see three arrows, which are identical in terms of the two images which comprise them, but which have different names. They have to, otherwise placing the mouse over any one of the links would cause all three arrows to change simultaneously. This time, the rollover image is not itself a link; rather, the onmouseover and onmouseout events are placed within the active <a> tag surrounding the nearby text. But there's no reason why the event and the image being changed even need to be particularly near each other, though obviously they have to be on screen at the same time, otherwise the procedure is nearly pointless.

Of course you could "roll" between two images that were only vaguely related, if at all. I think this is a waste of time, though; if you want to show two images on a page, show them both in the ordinary fashion. Remember also that in the virtual lecture I combined this technique with a multipart image and made only part of the image roll over, which had a strong visual impact. Also remember that if you are using the technique for any image that is larger than a few Kb - that is, almost all images - you should really preload the image, as if the new image isn't in your cache, the time taken to load it up can completely spoil your use of this technique. See the next section for details.

A final word of warning - do give the reader cause to place their mouse over a rollover image. If there's one there, tell them about it! Also, don't "hide" important information under a rollover. It's very irritating to come to a page and find that the author has gratuitously hidden half the content simply to show off their mastery of the rollover technique. (Some critics of this style have called it "mystery meat" - like the "meat" in certain take-aways, you don't know what it is until you've taken a bite, and then you might not like it.) As ever, if you're going to do this sort of thing, have a point. But it's very common, and once you've got the two images, quite easy to produce eye-catching effects. It's main use is in livening up your menu bars, and more detail comes on this in lesson 10.

8.2 preloading

With all the image-changing tricks we've used so far, whether with full or multipart images, there is one big problem. This is that images take time to load, and the browser viewing the page does not start to load the images until it is instructed to. The way around this problem is to ensure that the images in question are in the viewer's cache before they are required (see lesson 6).

It's not always easy to convince people of the need for this because at university, download times are very fast, and many homes now have broadband access which is almost as speedy, at least for smaller images. It may be, then, that when you come to the examples below, you'll ask, "what is he going on about?" as the download times for each example will be negligible. I suggest, if possible, you look at this page from a PC with dialup access (56Kbps) if you remain unconvinced. I also suggest, while we're on the subject, that you look at all your course work web site on a home PC, or ask a friend/relative with dialup Net access to do so for you. It's another way to make sure your web site is accessible.

Anyway: there are various ways to get images into your cache before they are needed. We did discuss one trick on the page about the cache. That was, to load a "super-dense", 1 × 1 pixel version of the image while the user was happily reading something else. But that might not be possible all the time, and in any case, it's a bit of a cheat. Much better to use JavaScript to preload the image into the cache. This also gives me the opportunity to introduce the second main method of including JavaScript on your site: not as single "events" located within tags, but as sets of instructions which are known as scripts.

This is the first time we will actually encounter proper JavaScript, as opposed to JavaScript events (like onMouseOver). A lot of this will still look like hieroglyphics at this stage. Don't worry about it though: just faithfully repeat it in your code - you can find out what it actually means soon.

To get an images into the viewer's cache before they've actually seen it, you will have to include in the <head> of your HTML file a JavaScript routine which pre-loads any images which are not visible when the page is first loaded. (There is no point in pre-loading images which appear when the page is first loaded, as the very act of displaying the images ensures that they arrive in the viewer's cache.) A further advantage of this method is that you can include in the image pre-loading script a line which checks before running the script whether or not the viewer's browser can handle image changing, which means that people with older browsers which perhaps cannot deal with image objects will not attempt to run the script - making your page backwards compatible with older browsers.

The basic image pre-loading (and changing - whilst we are putting stuff in the head of the document we might as well put it all there) script looks like this:


<script type="text/javascript">
<!--
no1 = new Image(190, 206);
no1.src = "jupiter.jpg";
no2 = new Image(190, 206);
no2.src = "jupiterpainted.jpg";
function changeimage (imgTagName,imgObj)
{
  if (document.images)
    {
       document.images[imgTagName].src = imgObj.src
    }
}
// -->
</script>

It shouldn't be too hard to adapt this to your requirements - remember it goes before the </head> tag. The script starts by loading the images. The first image to be loaded is called jupiter.jpg, and (like the other) it is 190 pixels tall by 206 pixels wide. This image is given the label "no1", for reference. The next image is called jupiterpainted.gif and is given the label "no2". The part of the script which actually loads the images is the no1.src = "jupiter.gif"; which updates the source of the image. The rest of the script, as you may be able to guess, actually does the image changing. The function takes two values (imgTagName, and imgObj), and after checking to see that the browser can handle image objects (which is what if (document.images) does) it says 'swap whatever the source for imgTagName is with the source for whatever imgObj is'. (.src in a JavaScript or HTML context stands for source). This new script means that in order to change images all you have to do is call the function changeimage with the correct parameters - namely, two images which are mentioned in the preloading bit of the script.

So, to invoke the script above (which is also in the head of this document) all we need to do is to include the following code in our HTML file (the link could be a real link even though I have left it as a dummy here):


<a href = "#"
 onmouseover = "changeimage('planet',no2)"
 onmouseout = "changeimage('planet',no1)">
<img name="planet" src="jupiter.jpg"
 width="190" height="206">
</a>

Ideally you should preload all images that are involved in rollovers, unless they are very small (like the arrows used in the second example in the rollovers page), and/or you know they will already be in the cache.

8.3 more JavaScript events

Image rollovers were the first time we saw the use of JavaScript events to cause changes on your web pages. But there are more possibilities here than this. 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 events.

Alerts have not yet appeared on this site. I will mention them now, as they provide a useful illustration of the technicalities involved, and of the distinction between the most common events. These are onclick and the two we've already seen: onmouseover and its complement, onMouseOut. In this example you would click on a button to see the alert:

<form action="">
<input type="button" value="Click on Me!"
  onclick="alert('This is not so irritating, and could conceivably be useful'); return true" />
</form>

Like onmouseover, onclick is an "event". There are other event handlers you can use - 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). Links and form elements (boxes and buttons) can include onfocus. The table below details the common JavaScript event handlers:

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 section 8.1 above:

<a href="#" onmouseover="document.baby.src='joe2.jpg';" onmouseout="document.baby.src='joe2bw.jpg';">
<img src="joe2bw.jpg" name="baby" alt="Rollover image demo /">
</a>

Now we can see that 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 8.6 below.). 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.

Here's a simpler object which has been used on some of the demonstration pages, where you can close a window by clicking on a link. The link looked like this - don't forget the empty brackets:

<a href="#" onclick='window.close()'>Close this window</a>

Use of the onunload event is how 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 is used on the form-based menu (see 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 more fun and frolics with this kind of thing (my, we're full of it today), see the Changing Background Colours page (http://www.leeds.ac.uk/acom/webdesign/materials/ext_backcol.html).

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 could use the following code to make this change:

<a href="lesson8.html"
  onmouseover="window.status='Return to the menu for lesson 8 (JavaScript)';
  return true;">Back to the menu for lesson 8</a>

(To make these more sensible you should really add
onmouseout="window.status=' ';"
as well.)

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.

8.4 the <script> tag

8.4.1 scripts v. events

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).

However, there are also advantages to be gained from moving scripts out of the confines of tags. It is possible to define a 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.6 below). This is where the <script> tag comes in.

Again it is useful to refer back to a previous section - 8.2, to be exact. 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 for which you'll be using this) 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 XHTML 1.0 standard, and will therefore not validate. type will, however.

The only other thing to really draw attention to at the moment is 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 8.5 below.

8.4.2 Ready-made scripts

Although you might be thinking JavaScript is way too complicated for you to start incorporating into your pages, there is a cop-out solution (which I use all the time myself...). Many sites act as "libraries" which feature scripts that anyone can use in their page as long as they include a link referring back to the original site. See, for example, http://javascript.internet.com/, the JavaScript Source.

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.

8.5 starting with functions

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.

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". (It's the same on style sheets, where the { marks the beginning of a single set of instructions and the } marks the 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". 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 (again, there is a parallel in style sheets). 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 this simple example. The code below would create a text box and then, when the button is clicked, display an alert reading "Hello X" where X is whatever the user typed in the box:

<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>

8.6 further JavaScript

You may have noted on the previous page that we were able to 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. The example in the online materials opens a variety of new windows, but without including long onclick events in each link, 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.html');">

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.)

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.html", "bolivia.html" 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 go back to the "opening new windows" section (lesson 10) and compare the code of the two methods, to see which one you ultimately prefer.

Going on from here

There have been several occurrences 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 lecture 8.