Web Application Development
Lab Class 2 Autumn 2010 Aim: This lab class is an introductory tutorial in client‐side programming in JavaScript. We will use very basic html markup and no style sheets. So this lab class should be quite accessible to Maths Department students with no prior experience in these topics. The lab class does, however, assume a basic familiarity with computer programming. The constructs used are quite simple, but do ask one of the demonstrators for further explanation if you do not understand any details. In contrast to the remaining tutorials, you will be guided in some detail in this one. But please do make sure you understand every step. You will need to in order to progress with the following tutorials. Again, do ask if you have any doubts in your mind about how things are working. Most of these examples are taken from, or slightly adapted from, Ajax
Programming for the Absolute Beginner, by Jerry Lee Ford, Publ: Course Technology. Details of Task 1 (Dynamically Displaying Text): This task provides a basic introduction to using JavaScript to programmatically replace text in a web page without screen refresh. We will use a very simple approach, which exploits the Document Object Model that we revised in last week’s lecture. Open a new Java Web Application Project in NetBeans. You should remember how to do this from last week’s tutorial. The choice of project name is yours, but try BasicJavaScript if you can’t think of anything. Use GlassFish V2 as server, and
Java EE version 5, then click Finish. You will find that a file index.jsp has been created under Web Pages. This is the file you will edit in this task. Change the text between the title tags in the head section of the html to: “Demo: Dynamically Displaying Text” Now you are going to define a JavaScript function in the head section. You should remember the tags you need to wrap the JavaScript in from last week’s lecture. Enter these and then insert the following function definition: function GreetPlayer() {
document.getElementById('GreetingMSG').innerHTML =
"Well, hello there!";
}
What this is doing is retrieving a reference to an element in the html document that has ‘GreetingsMSG’ as identifier. It is then using the innerHTML property of that object to write a new text string to the respective element. Although we can define the function in the head section, we cannot call it there as the element that is referred to will not have been parsed when the head is loaded into a browser. Let’s now look at the body section. First of all, change the text between the tags to: “Knock, Knock” (Yes, this is a pretty silly example. But it demonstrates a useful technique.) Now we need to create the element that the function will write to when called. Insert the following division underneath the level 1 heading:
This is simply a named division with an empty line in it. Now for the magic. We will create a form that contains a single element ‐ a button. Clicking the button is an event (again, refer to last week’s lecture), which will trigger a call to the function we defined in the head of the document. So add in the following under the div:
Once you have done that, run the project. After the web page has opened, click on “Open Door” to see what happens. Yes, you guessed it, but it is quite nice if you have seen this for the first time (but after that, …).
Details of Task 2 (Clock): You will explore two things in this task. Firstly, you will see a way of recursively calling a function to achieve some continuous behaviour. Secondly, you will see a method for accessing a different part of the brower Window – the status bar. We are going to put a digital clock into the status bar that updates once a minute. Open a new Java Web Application project, as before, and call it Clock or
DigitalClock or something similar. In the head, change the title to “Digital Clock” (why not!). Now we are going to define a display_time() JavaScript function in the head. (you should know what to do to start this off by now!). Before you start entering the function definition between the script tags, you might like to enter the following comments:
// Invoke this once to display the clock;
// it will call itself from then on This is one way of identifying a comment in JavaScript. Everything from “//” to the end of a line will be treated as a comment. Now lets start the function definition. Enter:
function display_time() {
var d = new Date();
} That gets us the time and date, but we only need the time and that is currently in 24 hour clock format. So let’s pick out the time and turn it into a 12 hour clock (I’m sure you understand a 24hr clock. It’s just an exercise to learn how to do things in JavaScript!). So, a quick update is needed to this:
function display_time() {
var d = new Date();
var h = d.getHours(); // Extract hours
var m = d.getMinutes(); // Extract minutes
var ampm = (h >= 12)?"PM":"AM" // Convert to 12 hr format
if (h > 12) h -= 12;
if (h==0) h = 12;
if (m < 10) m = "0" + m;
} Do note the following:
• We are using two “accessor methods” on the Date object d to get the hours and minutes;
• We obtain “AM” or “PM” from a simple “if, else” statement. Note the syntax;
• We use a simple “if” statement to decrease the hours by 12 (‘‐=’) if they are in the second half of the 24 hr clock;
• The ‘+’ operator is “overloaded” so that it can be used to append strings, as well as add numbers ( and if a number is “added” to a string, it is automatically converted to a string representation – the same would happen in Java, incidentally). Now we have all the bits (hours, minutes, and whether it is morning or afternoon). But we need to compose these into a single string. So append the following at the end of the function definition; var t = h + ':' + m + ' ' + ampm;
defaultStatus = t; These two lines construct the string representation of the time, and then write it to the status bar at the bottom of the browser window. We are not quite there yet, however. What we want to do is have the time update once a minute. We can do this with the built in setTimout() method. This takes two arguments. The first is the function to be called, and the second is a delay in milliseconds, after which the respective function will be called. We actually get the function to call itself after 60 seconds (60,000 milliseconds). This recursive call will go on ad infinitum (or until the page is closed, whichever is the sooner). So finish the function definition off with these lines:
// Do it all again in 1 minute
setTimeout("display_time()", 60000); That gets the function defined. Now we can call it when we load the body of the document. Edit the body so it looks like this:
Look Below
Now run the project, and hopefully you should see the clock in the status line at the bottom of the window.
Details of Task 3 (Number Game): We will talk a bit more about variable declarations in the lecture tomorrow. But for the moment, note that all the variables that are declared using the var keyword, in the function definition above, are only “scoped” within the function itself. That is, their values cannot be accessed from outside the function. If you want to declare a globally accessible variable, this is generally done by declaring it outside a function body (it can be done within a function, but we will talk about that tomorrow). Anyway, you are clearly getting the hang of this now so let’s look at a more complicated programme. This is for a simple guessing game. Start a new project (you should be used to this by now), and edit the html document until it looks like the following page. Work through steadily. NetBeans will help you with the nested while loops. Note:
• The use of “==” to check equality. “=” is an assignment operator, not a test.
• A while loop will continue to execute until its associated condition is false. You should by now be able to understand the functionality of this programme. It will pick a number between 1 and 10 at random. The user will be asked to guess the number. If the user guesses the number correctly, they will be notified and asked if they want to play again. If they guess incorrectly, they will be asked to guess again. If they guess correctly and don’t want to play any more, then the game will terminate with a polite message. Make sure you understand the program. If in any doubt, ask, because you are now going to modify it. 1. First, make the game more challenging by increasing the range of numbers supported by the game to 1 to 100 (or 1 to 1000, if you want to have more fun). 2. Second, modify the game so that as well as saying if the player’s guess is too high or two low, it also provides feedback if the guess is close to the number (you can choose how to interpret “close”.
Ajax Programming for the Absolute Beginner contains a more detailed description of this program.
A Number Guessing Game
Guessing Game
Details of Task 4 (Browser Details): If you have time, you might like to explore this a little. JavaScript supports a navigator object that contains information about the browser as a whole, not just the window it is executing in. You can access this to find out about the browser your web page is executing in, and perhaps modify its behaviour if needed. Let’s just look at the information you get for now. Open another new project. This time, start by opening a new JavaScript file in Web Pages. Edit that file so it looks like the following:
/*
* File: browser.js
* Include with:
*
* A simple "sniffer" that determines the browser version and vendor
* It creates and object named "browser" that is slightly easier to
* use than the "navigator" object.
*/
function BrowserInfo() {
// Create the browser object
var browser = "Browser Information:\n";
// Now copy the navigator information into "browser"
// with some formatting:
for(var propname in navigator) {
browser += propname + ": " + navigator[propname] + "\n"
}
alert(browser);
} Basically, this extracts all the properties from the navigator object, and formats them into a neatly constructed list. It then displays all the details in an alert. You display the alert by editing within the html tags of index.jsp to get:
Browser Info.
Browser Info.
Note the method of loading the JavaScript file (see also the lecture notes). Try running this to find out all about your browser.