![]() |
![]() |
|
|
|
||||||||||||||||||||||||||||||||||||
Lab #12Introduction to JavaScript12.1 What is JavaScript?JavaScript is another tool that can help provide additional features to your web pages. However, before we get into the details, we need to clear up a few things. First off, JavaScript is not Java. Java is a programming language created in 1995 by Sun Microsystems. Java is used to create both computer applications and small programs (known as applets) which can be placed in a browser. While applets are still found on the web, Java is more widely used in the creation of applications (programs).JavaScript however, has little to do with Java, other than that they both evolved around the same time. JavaScript is a scripting language which is used to provide program-like functionality in web pages. JavaScript can be executed before web pages leave the server (server-side), or once the page is loaded into a browser (client-side). We will concentrate on the latter. Another point to mention when talking about JavaScript is compatibility with browsers. Originally introduced by Netscape for use in their Navigator browser, Microsoft followed suit with a similar feature to their browsers. Over time, both companies had their own similar, but different versions of client-side scripting. Therefore, in this lab, we will try to introduce only concepts and examples that will work for both browsers. In addition, the issue of compatibility means that when you are creating web pages which involve the use of JavaScript, you need to check the pages against more than one web browser. Experienced developers will check their pages with both Microsoft's Internet Explorer and Netscape's Navigator browsers. Another popular browser is the Mozilla browser, which is the underlying browser engine for Netscape's new browsers. As Mozilla's popularity grows, so too will the need to check web pages against Mozilla as well. (Mozilla was used in creating the screen captures and HTML editing of this series of labs.) Back to JavaScript... Client-side JavaScript is a series of interpreted procedural or object-oriented statements weaved into a web page. (See your textbook for more information about procedural and object-oriented programming languages). When included in a web page and the page is then loaded in a user's browser, JavaScript can:
12.2 Getting Started with JavaScriptTo insert JavaScript into our web pages, we must place the script tag (<script>) in our web page at the desired location for the script (more on this later!). To start with a simple example, we can add a JavaScript alert window to our web page by inserting the script tag and the code for the alert in the header of the document, as in the following code:
When the web page in the example above is loaded by the user's web browser, an alert is displayed for the user. The contents of the alert are specified in the alert function call made in the JavaScript statement. The resulting (initial) display is shown in Figure 1, below.
Taking things a bit further, we can declare a variable in our JavaScript and place a user-entered value in it for use later in the web page. In the example below, we display a prompting window with the question "What is your name?". The prompt window will remain displayed until the user clicks the OK button. (Presumably the user has first answered the question in the text area, but there is no guarantee of this happening!) Next, as the document is being rendered in the browser, we print the value of the user's entry as part of the H3 tag. This second step is accomplished by using the document.write method call. In JavaScript the document is a JavaScript object (as in object-oriented programming) which contains a method (function) named write. By calling the write method and passing it a string (text enclosed in double quotes) we can modify the actual HTML document by providing custom HTML on-the-fly (as it happens)! Figures 2 and 3 show the results of the prompting window and the resulting HTML document once it finally completely loads.
12.3 Other things we can doJavaScript has a number of built-in objects and functions which we can use within our scripts. One example of this is the Date object which can be used to create and manipulate calendar dates. Once these date objects are created, we can manipulate them or extract information from them.For example, in the code below, we have added the creation of a new Date object (dateNow) to web page. Then, in the body of the page, we can extract and print our date information. (To keep the example simple, we have purposely placed nothing else on the web page, and limited the formatting to a bare minimum!)
If you use this code on your web page, you are likely to notice two things:
For the second problem, we will need to check the value and prepend a "0", if needed (if the value is <10). To accomplish this, we will need to utilize two simple 'if' statements as well as introduce two additional temporary variables. Both of these solutions are reflected in the code below and are followed by a screen capture of the resulting page.
Next, we will make the page a tad more complex. If we would like to update the time, we currently have to reload the page. However, by inserting a form and a function that recalculates and displays the time, we can have the function update the clock's time. To accomplish this, we will add the form, our text in the form, and a text field to display the clock's time. We will also add the updateForm function to recalculate and update the results. Finally, we will add a timer to make it all happen. The source code is listed below.
The JavaScript code in the body of the web page is really processed first. When this happens, the initial display of the date and time takes place. Notice that we neglected to correctly format the minutes and seconds to save a little space and to keep the example easy to read. Pay particular attention to the form (named timeForm), text field (named timeField). They become important in the updateForm function. Once the page loads and the form is displayed, we set a timer (the setTimeout call) to call our function updateForm after 1000 milliseconds (1 second). Then, after 1 second, the updateForm function is called. Within the body of the function, a new Date object is created, the appropriate values obtained and then formatted using a few extra temporary variables (minvalue and secvalue). Next, the form updates the value of the timeField in the timeForm, which updates what is displayed to the user (thereby updating the clock). Before the function is done, we reset the timer (call setTimeout again) so that the form is updated in another second. One last thing to point out with this example is that we only change the hours, minutes, and seconds in the updateForm function. If you watch the form for a long enough time you will notice that the day, month, or year do not change! This is not a bug, it was done by design (to keep the example simple, and to lead you to Lab Activity #2)!
12.4 Checking web formsSpeaking of forms on the web... JavaScript is quite often used to validate user input on web forms before the data is sent to the server. In this fashion, we can reduce the processing load on the server by ensuring that the data has already been examined for errors or problems. Consider the following simple example:Let's say we have a form that asks the user to enter his or her name and email address. Before storing this information on our server (so that we can send them spam email later, for example), we wish to ensure that:
So first, we need our form. The code listing from javascript6.html will provide that for us. Figure 6 contains an image of this form in a browser.
Now that we have our form. We'll want to create a function that checks the values of both fields in the forms when the user hits the "Submit results" button. Essentially this function will display an alert window if it finds an error. The function listed in javascript7.html (below) is the function which will perform our form validation for us. For each piece of data (the user's name and email address), we first copy the value to a temporary variable. Next, we set a flag (valid) to true. This flag will indicate if the form is free of errors (and initially we will assume it is). Next, we check the length of the namevalue temporary variable. This variable currently holds the contents of the form's textfield named 'username'. If the length of the value is <1 character long, then we know it was not filled in and left blank. If this is the case, we present the user with an alert message and set our valid flag to false. We next examine the emailvalue variable's length (to see if it is blank) and if it contains an at-symbol. To check for the symbol, we will use the indexOf method and pass it the at-symbol character. If the symbol is not present in the variable emailvalue, then the method will return a -1 value to us. So, if either the length is less than 1 character, or if the value does not contain the at-symbol, we present an alert to the user and set the flag.
Finally, as the function finishes, we return the value of the valid variable. How we tie it all together is the subject of the next bit of code... We will add the onSubmit attribute to the form tag in our web page. The onSubmit attribute will call the specified function (checkForm) and obtain the result returned by the function. If the value is 'false', the form will not be submitted. If the value is anything else, the form will then be submitted to the server for processing. Thus, our final result looks like the following:
12.5 More with JavaScriptTo keep this lab short, we have had to remove a lot of material about JavaScript. Because of this, we could do an entire series of labs just on JavaScript. For example, we could talk all about the various data types in JavaScript, how you can modify the browser's status bar, how to import JavaScript from another source file, and on. One area that needs a good deal of attention is how to script and support older browsers. If you get into serious JavaScript development, you would definitely want to purse this topic even further.This lab however, is only meant to be an introduction to the capabilities that JavaScript can bring to your web pages. In the next lab, we will see additional uses of JavaScript, as we combine CSS and JavaScript to get Dynamic HTML (DHTML). But, before we go, here are a few short tasks to complete regarding JavaScript.
About the labs: These labs were developed in conjunction with the Jones and Bartlett textbook Computer Science Illuminated by Nell Dale and John Lewis. ISBN: 0-7637-1760-6 Lab content developed by Pete DePasquale and John Lewis. |
![]() |
![]() |
![]() |
|
|
|
|||