Web Design Small Cover

Buy the PDF of
Web Design:
A Complete Introduction

See the book at amazon.co.uk or amazon.com

Related Site

Web Security Topics

Related Books

Secure Communication Cover

Securing A Server Cover

Answers to Exercises, Chapter 7

Test Questions

  1. Features that you will find commonly implemented using scripting include rollovers (see Practical Task 3), image swaps, form input verification (as described in the book), pop-up windows and drop-down menus. Less frequently you may see simple animation and transitions implemented in this way, and on so-called Web 2.0 sites you will find examples of drag and drop and type-ahead completion. Rollovers, as we have shown, can be implemented in CSS instead; the technique can be extended to make drop-down menus. Form data verification can be performed on the server instead of in the browser, and animation is more usually done using Flash or animated GIFs than with scripting. The other features cannot easily be done except by JavaScript, because they require the page to be altered in response to user input, without fetching a new page from the server.
  2. The object corresponding to the div element with id equal to navbar is obtained by the expression document.getElementById("navbar"). To obtain all the img elements inside some object e, you would use the expression e.getElementsByTagName("img"), so to obtain all the img elements inside the div with id equal to navbar, as required, we just combine these two expressions:
    document.getElementById("navbar").getElementsByTagName("img")

    If you find this too terse, just assign the div object to a variable e.

  3. Each time round the loop, one element is removed from the collection of children. Those following it, therefore, move up: if the first child is removed the first time round the loop, then the former second child becomes the first, the former third becomes the second, and so on. The next time round the loop, one is added to the value of i, so the second child is removed – that is, the new second child, formerly the third. The original second child, having become first, is left in place. And so it goes on, with only half the children being removed. If you want to delete all a node's children, just keep deleting the first until there are none left.
  4. The general form of the for loop is
    for (initialization; test; step) body

    which is equivalent to

    initialiation;
    while (test) { body; step; }
    

    The for loop is provided for two reasons. A simple for loop, where the initialization sets a variable to 0, the step adds 1 to it and the test compares it with a maximum value, captures a very common pattern of computation where something is done to every element of an array. (The loop variable is used as an index in the body.) This is probably why the for loop was invented. The more elaborate general form found in JavaScript was taken from C. Here, the additional advantage of this form of loop is that all the calculation concerned with moving on to the next iteration and checking whether the loop is finished is kept together in one place. This makes thinking about what is happening in the loop easier than if they are separated, as in the equivalent while loop just shown.

  5. A handler for this event could, in fact, be used to attach handlers to any other element, since the load event occurs when all of the page's content has been loaded. The problem is attaching the load handler to the body, since if it is to be executed when the load event occurs, it must have been attached beforehand. This can only be done by way of the onload attribute, but using attributes in this way interferes with the principle of unobtrusive scripting – the script is embedded in the markup, which is considered undesirable nowadays.
  6. Any time you wish to respond to a mouse drag, you need to detect the mousedown event at the start of the drag, and the mouseup event to determine when the drag ends. This will be the case if you implement a drag-and-drop interface in JavaScript, or use controls such as sliders, which are operated by dragging.
  7. An element receives a focus event when it gains the input focus, so you would obtain an object for each of the form's controls, probably using getElementsByTagName, and then assign a function to its onfocus attribute, which performed the highlighting.
    control.onfocus = highlight;
    

    You would define the highlight function appropriately, perhaps by altering its className attribute in the way we describe in the book, so that a CSS rule that draws a border round it becomes applicable.

    You only want the highlight to show while the control has the focus, so you must also set a handler for the blur event, which reverses the effect of highlight.

    control.onblur = unhighlight;
    
  8. The first reason for not relying on JavaScript for validation concerns the browser: it might not support JavaScript, or the user might have disabled JavaScript. In either case, the validation would not be performed. The second reason concerns the server: a request to the script that processes the form does not necessarily result from a user filling in the data and clicking submit. Requests can be generated and sent directly, using curl, for instance. Such requests by-pass any JavaScript checking and go straight to the server-side script, which must, for both these reasons, be prepared to deal with invalid data.
  9. The code only works correctly if the id values have a digit as their fifth character that corresponds to the number of years. There are at least two ways in which this might go wrong. First, if it was decided to extend the application to handle long-term loans over more than nine years, the second digit of any two-digit periods would be ignored. Second, if somebody wished to tidy up the markup for the form and in so doing changed the ids, perhaps to conform to some site-wide naming convention, then the assumption about the relationship between the id and the loan period would become invalid. One better way would be to set up an associative array mapping ids to periods. Arbitrary ids could then be used and mapped to periods of any length.
  10. Using click handlers and XMLHttpRequest to fetch the pages pointed to by links would be possible, but not sensible. Nothing would be gained, since the same number of requests and responses would have to be sent, and the same data would have to be retrieved. Extra unnecessary work would be required to attach all the handlers, but more seriously, the history list and back button would no longer work – everything would appear to be a single page – disrupting users' expectations of how the Web works. Finally, unless care was taken, it is possible that users with JavaScript disabled would find themselves unable to follow links.

Discussion Topics: Hints and Tips

  1. Adding an extra assistant doesn't introduce any new sorts of thing (classes) into the situation, we only need another instance – for the purposes of this exercise, one assistant is the same as any other. What does change is the way in which they serve customers. With two people serving, the possibility of parallelism – two customers being served at once – arises, and your model would have to take this into account.
  2. The usual way of doing this is to add a div in front of the entire page, with a simple loading message, and make it invisible once the page has finished loading. The tricky bit is ensuring that users with JavaScript disabled get to see the page and not just the loading message. This means you have to create the loading message at an appropriate point using a script.
  3. One way is to provide alternative versions of Web applications, one for mobile devices and one using AJAX for conventional browsers. A better way to proceed is by ensuring that, in the absence of JavaScript, the application falls back to a mode of operation where all computation is done on the server and interaction only relies on XHTML features. This can be done by creating the Web application so that it works without JavaScript and then adding handlers to enhance it for browsers with scripting support, a method sometimes called Hijax. Note that The W3C Mobile Web Initiative's mobileOK scheme appears to assume that Web content will not work on mobile devices if it relies on scripts.

Practical Tasks: Hints and Tips

  1. There is no need for tricks or cleverness in this function. All you need to do is set up a loop that iterates through the characters of s1, and realize that the character you need to replace s1.charAt(i) is s2.charAt(i), for any i – provided the replacement character exists. It may help to write a separate function to do the replacement of an individual character. The only slightly tricky part is ensuring that your function does something sensible if s2 is shorter than s1. (First decide what constitutes something sensible in that case.) You can test your function before creating the test form, by setting arguments explicitly in the code and using the window.alert method to display the result: window.alert(replace_characters("the target", "aeiou", "uoiea")), for instance.

    The second part of the task is slightly more complicated. You need to set up a form with four text input fields: three for the arguments and one for the result. You will also need a button with a handler to call the function you are testing. Look through the section on validating form data and the repayment calculator example to see how to get data from and write it to the fields. Can you make this into a more general test rig for JavaScript functions?

  2. This is just an exercise in using the DOM methods that rearrange the tree: you need to take the first child and append it to the end of the descendants of the navbar element.
  3. This is the classical technique of creating rollovers by swapping images using JavaScript, which you will find all over the Web. Before CSS provided the :hover pseudo-class, this was the only way rollovers could be implemented. Recall from the image gallery example that changing the value of the src attribute of an img element causes a new image to be displayed.
  4. Start by making the navbar with all the second level links visible, and then hide them with CSS and add the mouseover and mouseout event handlers to make them appear and disappear. Changing the className property may be the easiest way.
  5. Do this for yourself first, then take a look at this popular stylesheet switcher implementation. Note how he uses cookies to make the choice of stylesheet persist throughout the site, a refinement we did not include in our className-based switcher, but which is essential for any site with more than one page.