Chapter 3: JavaScript in Action Page 1 of 10. How to practice reading and writing JavaScript on a Web page



Similar documents
Advanced ColdFusion 4.0 Application Development Server Clustering Using Bright Tiger

Setting Up Your Internet Connection

Teach yourself Android application development - Part I: Creating Android products

Early access to FAS payments for members in poor health

Vision Helpdesk Client Portal User Guide

How To Protect Yoursef Onine From Being Hacked Onine

A Description of the California Partnership for Long-Term Care Prepared by the California Department of Health Care Services

Art of Java Web Development By Neal Ford 624 pages US$44.95 Manning Publications, 2004 ISBN:

Pay-on-delivery investing

NCH Software Express Accounts Accounting Software

Bite-Size Steps to ITIL Success

Avaya Remote Feature Activation (RFA) User Guide

The guaranteed selection. For certainty in uncertain times

AA Fixed Rate ISA Savings

TERM INSURANCE CALCULATION ILLUSTRATED. This is the U.S. Social Security Life Table, based on year 2007.

Introduction to XSL. Max Froumentin - W3C

The Web Insider... The Best Tool for Building a Web Site *

ELECTRONIC FUND TRANSFERS YOUR RIGHTS AND RESPONSIBILITIES

READING A CREDIT REPORT

DISPLAYING NASDAQ LEVEL II DATA

Let s get usable! Usability studies for indexes. Susan C. Olason. Study plan

NCH Software FlexiServer

Chapter 2 Traditional Software Development

NCH Software BroadCam Video Streaming Server

WEBSITE ACCOUNT USER GUIDE SECURITY, PASSWORD & CONTACTS

Finance 360 Problem Set #6 Solutions

NCH Software MoneyLine

A short guide to making a medical negligence claim

Chapter 3: Investing: Your Options, Your Risks, Your Rewards

NCH Software Copper Point of Sale Software

NCH Software Warp Speed PC Tune-up Software

DigitalKitbag. marketing

I m pretty lucky as far as teen librarians

ELECTRONIC FUND TRANSFERS YOUR RIGHTS AND RESPONSIBILITIES. l l l. l l

Design Considerations

ELECTRONIC FUND TRANSFERS YOUR RIGHTS AND RESPONSIBILITIES. l l

A guide to understanding Childcare Proceedings

SNMP Reference Guide for Avaya Communication Manager

Understanding. nystagmus. RCOphth

ELECTRONIC FUND TRANSFERS YOUR RIGHTS AND RESPONSIBILITIES. l l. l l. l l. l l

ELECTRONIC FUND TRANSFERS. l l l. l l. l l l. l l l

CSCI 8260 Spring Computer Network Attacks and Defenses. Syllabus. Prof. Roberto Perdisci

Lucent Technologies Bell Labs Innovations. PARTNER II Communications System PARTNER Plus Communications System Release 4.1.

In some states, however, the couple must live apart for a period of months or years before they can obtain a no fault divorce.

Teamwork. Abstract. 2.1 Overview

TCP/IP Gateways and Firewalls

We are XMA and Viglen.

Licensed to: CengageBrain User

NCH Software PlayPad Media Player

Technical Support Guide for online instrumental lessons

What makes a good Chair? A good chair will also: l always aim to draw a balance between hearing everyone s views and getting through the business.

Example of Credit Card Agreement for Bank of America Visa Signature and World MasterCard accounts

New Features in Cisco IOS 12.4

How to Cut Health Care Costs

LADDER SAFETY Table of Contents

How To Make An Audio Fie On Mixpad

Business schools are the academic setting where. The current crisis has highlighted the need to redefine the role of senior managers in organizations.

ELECTRONIC FUND TRANSFERS YOUR RIGHTS AND RESPONSIBILITIES. l l

Life Contingencies Study Note for CAS Exam S. Tom Struppeck

ELECTRONIC FUND TRANSFERS YOUR RIGHTS AND RESPONSIBILITIES. l l. l l

Chapter 3: e-business Integration Patterns

Figure 1. A Simple Centrifugal Speed Governor.

Business Banking. A guide for franchises

ELECTRONIC FUND TRANSFERS YOUR RIGHTS AND RESPONSIBILITIES. l l. l l. l l

So you want to create an a Friend action

Books on Reference and the Problem of Library Science

Chapter 3: Authentication and Resource Protection in Windows 2000

WHITE PAPER BEsT PRAcTIcEs: PusHIng ExcEl BEyond ITs limits WITH InfoRmATIon optimization

A practical guide to personal financial advice Finding the right financial adviser and advice that works for you. Getting advice

Accounting in the Construction Industry

Preschool Services Under IDEA

medical injury a claimant s guide

How To Get Acedo With Microsoft.Com

Excerpted from Content Strategy for the Web by Kristina Halvorson and Melissa Rach. Copyright Used with permission of Pearson Education, Inc.

What to do before, during and after a flood

Speech, language and communication. Information for managers and school staff

Operation Guide

ELECTRONIC FUND TRANSFERS YOUR RIGHTS AND RESPONSIBILITIES

Serving the Millennial Generation - The Challenge and Opportunity for Financial Services Companies

Health Literacy Online

THE GOTHAM GROUP PRINT& DISPLAY SOLUTIONS l 202 WEST PARKWAY DRIVE SUITE #2, EHT, NJ 08234

A Conversation with

NCH Software Crescendo Music Notation Editor

NatWest Global Employee Banking Eastwood House Glebe Road Chelmsford Essex England CM1 1RS Depot Code 028

On-Line Banking Application

Australian Bureau of Statistics Management of Business Providers

ADVANCED ACCOUNTING SOFTWARE FOR GROWING BUSINESSES

Order-to-Cash Processes

Integrating Risk into your Plant Lifecycle A next generation software architecture for risk based

Hedge Fund Capital Accounts and Revaluations: Are They Section 704(b) Compliant?

Secure Network Coding with a Cost Criterion

Operation Guide 5208

1B11 Operating Systems. Input/Output and Devices

WHITE PAPER UndERsTAndIng THE VAlUE of VIsUAl data discovery A guide To VIsUAlIzATIons

ELECTRONIC FUND TRANSFERS YOUR RIGHTS AND RESPONSIBILITIES

Breakeven analysis and short-term decision making

Lexmark ESF Applications Guide

IMPLEMENTING THE RATE STRUCTURE: TIERING IN THE FEE-FOR-SERVICE SYSTEM

MOS 2013 Study Guide. Microsoft Excel EXAM Microsoft IT Academy

Aviva Equity Release A guide to our lifetime mortgages. Lifestyle Lump Sum Max Lifestyle Flexible Option

Transcription:

Chapter 3: JavaScript in Action Page 1 of 10 Chapter 3: JavaScript in Action In this chapter, you get your first opportunity to write JavaScript! This chapter introduces you to JavaScript propery. In addition, this chapter is a big hands-on chapter in which you reay start to earn the fundamentas of JavaScript... by exampe! This chapter teaches you about the foowing: Some of the fundamentas of JavaScript, such as syntax, ayout, commenting code, and so on Some of the terminoogy of JavaScript and aso why it is known as an object-oriented anguage How to practice reading and writing JavaScript on a Web page How you can use JavaScript to create inputs and outputs Exporing JavaScript Inputs and Outputs Not ony are JavaScript inputs and outputs great for being abe to write JavaScript code that wi communicate two-way with the user, but exporing this area of JavaScript is aso a great pace to begin your journey to proficiency! Computing is a about inputs and outputs. Data goes in and data comes out. Without inputs and outputs, nothing woud happen and nothing woud get done. A word processor doesn t begin to do anything unti it receives input from the user (usuay in the form of characters generated by keystrokes), and this then eads to an output (it is outputted onto the screen and subsequenty to paper or eectronicay). Note - This chapter uses many sma exampes of JavaScript. I suggest you work through each exampe for yoursef, actuay typing out the code. The purpose of this is for you to get penty of practice with JavaScript basics before moving on to more compex JavaScript exampes. Repetition is the key to JavaScript success. Here, we are going to use JavaScript to contro inputs and outputs in the form of various types of message boxes (guaranteed, if you ve been surfing the Web for more than a few minutes, you ve seen these message boxes before!). Three types of message boxes can be conjured up using JavaScript. Figures 3.1, 3.3, and 3.5 show the Internet Exporer message boxes, whereas Figures 3.2, 3.4, and 3.6 show the message boxes of Netscape Navigator. Aert This is for outputting information.

Chapter 3: JavaScript in Action Page 2 of 10 Figure 3.1 An aert box dispayed by Internet Exporer. Figure 3.2 An aert box dispayed by Netscape Navigator. Confirm This outputs information and aows the user to input a choice in the form of a yes/no question. Figure 3.3 A confirm box dispayed by Internet Exporer. Figure 3.4 A confirm box dispayed by Netscape Navigator. Prompt This outputs some information and enabes the user to type in a response to the output. Figure 3.5 A prompt box dispayed by Internet Exporer. Figure 3.6 A prompt box dispayed by Netscape Navigator. Note - Why do the message boxes in Internet Exporer ook so different from the message boxes in Netscape Navigator? This actuay has nothing to do with JavaScript they are different because the aert, confirm, and prompt windows are generated by the browser. These boxes are ony triggered by JavaScript. Because of this, each browser adds its own uniqueness to the ook. aert(), confirm(), and prompt() are actuay a methods of the browser's Window object. Objects, Methods,... and Even Properties One thing you've probaby heard about JavaScript is that it is an object-oriented anguage. But what does this reay mean? To understand this, you need to be famiiar with three terms: Objects Methods Properties What foows is a brief ook at the three. After you have used JavaScript for a itte whie, you' find

Chapter 3: JavaScript in Action Page 3 of 10 yoursef using them a ot more, so we can eave the detaiing of them unti ater. Objects Put simpy, an object is a thing, anything. Just as things in the rea word are objects (cars, dogs, doar bis, and so on), things in the computer word are regarded as objects, too. To JavaScript, its objects a ive in the Web browser. These are things ike the browser window itsef, forms, and parts of forms such as buttons and text boxes. JavaScript aso has its own group of intrinsic, or buit-in, objects as we, which reate to things such as arrays, dates, and so on. At the moment, you don t need to think too much about these objects because they be covered ater; for now you just need to get some of the necessary terminoogy in pace. But it is objects that make JavaScript object-oriented. JavaScript is organized around objects rather than actions; to put it another way, it s organized around data rather than the ogic of the programming. Object-oriented programming takes the viewpoint that what you reay care about are the objects you want manipuated and not the ogic required to manipuate them. One of the benefits of this is that because you are freed from the ogic of the programming not ony is the process of programming (or scripting) easier, but there are aso many ways to perform a particuar operation. Methods Methods are things that objects can do. In the rea word, objects have methods. Cars move, dogs bark, doars buy, and so on. aert() is a method of the Window object, so the Window object can aert the user with a message box. Exampes of other methods are that windows can be opened or cosed and buttons cicked. The three methods here are open(), cose(), and cick(). Note the parentheses. Look out for these because they signa that methods are being used, as opposed to properties. Properties A objects have properties. Cars have whees and dogs have fur. For JavaScript, things such as the browser have a name and version number. Tip - It might hep you to think of objects and properties as things and methods as actions. Using the aert() Method aert() is the easiest of the three methods to use. You can use it to dispay textua information to the user in a simpe, concise way. When the user is finished reading the message, she simpy must cick OK to get rid of it. First, open your tempate HTML page in your favorite text editor and save it with a new name in a convenient ocation on your hard drive:

Chapter 3: JavaScript in Action Page 4 of 10 Note - Remember to save it with the fie extension HTM or HTML; otherwise, things won t work as panned. Warning - At this stage, it is probaby worth knowing that JavaScript is a case-sensitive anguage. You study this in much greater detai in future chapters, but for now, note that it is best to foow the choice for upper- and owercase etters for a JavaScript, apart from text strings that you want to use. To conjure the aert message box, type in the foowing: aert(); Note - The semicoon at the end of the aert() method is caed a ine terminator and is required to make your JavaScript ECMA compiant (athough it wi work propery without it). You wi see this a ot over the next few chapters; in Chapter 4, "Handing Data with Variabes," you find out exacty when and where it is used. Now, for the message that you want dispayed. This is paced inside quote marks inside the parentheses:

Chapter 3: JavaScript in Action Page 5 of 10 aert("an aert triggered by JavaScript!"); Save the page, oad it into the browser, and watch the message appear (see Figure 3.7)! Figure 3.7 An aert box compete with a custom message dispayed by Internet Exporer. Making a second aert appear is just as simpe as making the first one appear just add aert() to the <script> bock underneath the first and add your own message surrounded by quotes: aert("an aert triggered by JavaScript!"); aert("a second message appears!"); Save the fie in the text editor and refresh the browser. This time notice that two messages come up. But more importanty, notice how they are dispayed separatey, instead of one on top of the other. What this shows is that the JavaScript stopped between each and didn't just bindy run to the end of the script. It waited patienty unti the user cicked OK on the first box before going on to dispay the second. Tip - Remember to resave the fie before viewing the changes you've made. You woudn't beieve the number of users who forget this step and think they have done something wrong! Exercise - As an exercise, go back to the tempate and, from scratch, create a new JavaScript to trigger an aert box with a message of your choice. After you have done that, add a second aert box, foowing the same format. Next, add the aert() method on a new ine and then, inside the parentheses and in quotes, add the

Chapter 3: JavaScript in Action Page 6 of 10 message you want dispayed. Adding Comments to JavaScript Professiona JavaScripters strive to make it easy to reread their code when they come back to it (maybe many months ater). One of the things they use to hep them is the JavaScript comment tags, one of which you've aready come across in the previous chapter the singe-ine comment. Singe-Line Comments Here is an exampe of singe-ine comment tags in action: // The first aert is beow aert("an aert triggered by JavaScript!"); // Here is the second aert aert("a second message appears!"); If you run this JavaScript, you won't notice any difference at a. That is because the comment tags have done their job and hidden the comments from the browser's view. Muti-Line Comments Sometimes you need to add mutipe-ine comments to your scripts, and athough you coud go round pacing sashes (//) at the beginning of each ine, it isn't reay convenient. This is where the mutiine comment tags come into their own. Muti-ine comment tags consist of the open comment tag (/*) and then the comments themseves foowed by the cosing comment tag (*/). Here is an exampe of a muti-ine comment: /* Beow two aert() methods are used to fire up two message boxes - note how the second one fires after the OK button on the first has been cicked

Chapter 3: JavaScript in Action Page 7 of 10 */ aert("an aert triggered by JavaScript!"); aert("a second message appears!"); Adding meaningfu comments to a script is something that ony comes with practice. At first, it might seem tedious or even unnecessary, but not ony does it make your JavaScripts easier to understand, in the eary stages it heps you get a cearer idea of how your scripts work. Take every opportunity possibe to comment your scripts! Exercise - For the exampe you created for the previous exercise, comment your code using singe-ine and muti-ine comments. Using the confirm() Method The confirm() method works simiary to aert(), but this box is used to give the user a choice between OK and Cance. You can make it appear in pretty much the same way, with the ony difference being that instead of using the aert() method, you use the confirm() method. Note - The Cance button needs more JavaScript behind it than you have covered so far to make it work. Fear not, though; it wi be covered! So again, foowing the same routine as for the aert() method, you begin by adding the confirm() method to the script bock as foows: confirm(); And again, the message you want to appear in the box is typed inside the parentheses, contained in quotes:

Chapter 3: JavaScript in Action Page 8 of 10 confirm("which one wi you choose?"); Save the fie (again under a different name from the tempate and remembering to use the HTM or HTML fie extension) and oad it into the browser (see Figure 3.8). Figure 3.8 A confirm box compete with a custom message dispayed by Internet Exporer. Now notice the buttons on the box OK and Cance. However, at the moment nothing happens when you cick them except that the box disappears and the JavaScript continues to run again. Before you can use the buttons on the confirm box, you wi need a few more JavaScript skis, after which you wi revisit the confirm() method. Exercise - Practice adding the confirm() method to a Web page. Add your own messages. Add a coupe of separate confirm() methods to a Web page and note the resut. Using the prompt() Method The prompt() method is a itte different from the other two you have ooked at in the course of this chapter. This is the ony one that either aows the user to type in his own response to the question, instead of the script just processing information it aready has (as with the aert() method), or aows the user to choose OK or Cance (avaiabe using the confirm() method). You add the prompt() method in much the same way as the other two. To begin with, add the prompt() method to the <script> bock: prompt();

Chapter 3: JavaScript in Action Page 9 of 10 The prompt() method now starts to differ from the other two methods because two pieces of text must be added within the parentheses. The first is the message you want to appear. This is done in exacty the same way as before. Again, the text goes inside the parentheses and inside quotes: prompt("what is your name?"); Save this page and view it in the browser. Notice that the prompt appears, asking the user for his name (see Figure 3.9). You can type it in and proceed by cicking OK, or you can cick Cance. Figure 3.9 A prompt box with a custom message dispayed by Internet Exporer. Note the word undefined in the input box. This is an Internet Exporer feature; Netscape Navigator simpy eaves the box bank (see Figure 3.10). Figure 3.10 The same prompt box in Netscape Navigator; note that no text appears in the input box. At the moment, nothing reay happens no matter what you do, but by the end of this chapter you be abe to put this to work with a itte more JavaScript! Another piece of text we can add is the defaut text to appear in the actua input box of the prompt. Adding this is simpe and gets rid of the ugy ooking "undefined" that Internet Exporer dispays. Here is what you need to do. After the first piece of text inside the parentheses, pace a comma outside the quotes, and after that pace a second piece of text (again in quotes). Here is an exampe of this in action: prompt("what is your name?","enter your name here.");

Chapter 3: JavaScript in Action Page 10 of 10 Save the page again and refresh the browser. Notice how the once- empty input box now contains the text from the second set of quotes (see Figure 3.11). Figure 3.11 A prompt box with a custom message and defaut input box text dispayed by Internet Exporer. Exercise - Practice adding the prompt() method to a Web page. Add your own messages and defaut text for the input box. Add a coupe of separate prompt() methods to a Web page and note the resut. Add some comments (singe- and muti-ine) to your pages expaining what happens and what each part is. What s Next So far you ve seen how to dispay three kinds of message boxes using JavaScript. In the next chapter, you earn how to make these message boxes and other JavaScripts reay work by exporing two of the most important areas of JavaScript handing data with variabes and arrays. Copyright Macmian USA. A rights reserved