Beginning JavaScript

( 2 )


The perennial bestseller returns with new details for using the latest tools and techniques available with JavaScript

JavaScript is the definitive language for making the Web a dynamic, rich, interactive medium. This guide to JavaScript builds on the success of previous editions and introduces you to many new advances in JavaScript development. The reorganization of the chapters helps streamline your learning process while new examples provide ...

See more details below
$27.54 price
(Save 31%)$39.99 List Price

Pick Up In Store

Reserve and pick up in 60 minutes at your local store

Other sellers (Paperback)
  • All (14) from $13.33   
  • New (5) from $14.99   
  • Used (9) from $13.33   


The perennial bestseller returns with new details for using the latest tools and techniques available with JavaScript

JavaScript is the definitive language for making the Web a dynamic, rich, interactive medium. This guide to JavaScript builds on the success of previous editions and introduces you to many new advances in JavaScript development. The reorganization of the chapters helps streamline your learning process while new examples provide you with updated JavaScript programming techniques.

You'll get all-new coverage of Ajax for remote scripting, JavaScript frameworks, JavaScript and XML, and the latest features in modern Web browsers. Plus, all the featured code has been updated to ensure compliance with the most recent popular Web browsers.

  • Introduces you to the latest capabilities of JavaScript, the definitive language for developing dynamic, rich, interactive Web sites
  • Features new coverage of data types and variables, JavaScript and XML, Ajax for remote scripting, and popular JavaScript frameworks
  • Offers updated code that ensures compliance with the most popular Web browsers
  • Includes improved examples on the most up-to-date JavaScript programming techniques

Continuing in the superlative tradition of the first three editions, Beginning JavaScript, Fourth Edition, gets you up to speed on all the new advances in JavaScript development.

Read More Show Less

Product Details

  • ISBN-13: 9780470525937
  • Publisher: Wiley
  • Publication date: 10/26/2009
  • Edition number: 4
  • Pages: 792
  • Sales rank: 324,681
  • Product dimensions: 7.20 (w) x 9.20 (h) x 1.70 (d)

Meet the Author

Paul Wilton owns his own company, providing online booking systems to vacation property owners, which is largely developed using JavaScript.

Jeremy McPeak is a self-taught programmer who began his career by tinkering with web sites in 1998. He is the coauthor of Professional Ajax, 2nd Edition and several online articles covering topics such as XSLT, ASP.NET Web Forms, and C#. He is currently employed at an energy-based company building in-house conventional and web applications.

Read More Show Less

Table of Contents

Introduction xxv

Chapter 1: Introduction to JavaScript and the Web 1

Introduction to JavaScript 1

Where Do My Scripts Go? 7

Your First Simple JavaScript Programs 8

A Brief Look at Browsers and Compatibility Problems 15

Summary 16

Chapter 2: Data Types and Variables 17

Types of Data in JavaScript 17

Variables — Storing Data in Memory 20

Using Data — Calculations and Basic String Manipulation 26

Data Type Conversion 37

Arrays 40

Summary 49

Exercise Questions 50

Chapter 3: Decisions, Loops, and Functions 51

Decision Making — The if and switch Statements 51

Looping — The for and while Statements 71

Functions 79

Summary 84

Exercise Questions 86

Chapter 4: Common Mistakes, Debugging, and Error Handling 87

D’oh! I Can’t Believe I Just Did That: Some Common Mistakes 87

Error Handling 93

Debugging 103

Summary 131

Exercise Questions 131

Chapter 5: JavaScript — An Object-Based Language 133

Object-Based Programming 133

JavaScript’s Native Object Types 139

Creating New Types of Objects (Reference Types) 177

Summary 187

Exercise Questions 188

Chapter 6: Programming the Browser 189

Introduction to the Browser’s Objects 190

Responding to the User’s Actions with Events 199

Summary 215

Exercise Questions 217

Chapter 7: HTML Forms: Interacting with the User 219

HTML Forms 219

Other Form Object Properties and Methods 222

Summary 260

Exercise Questions 262

Chapter 8: Windows and Frames 263

Frames and the window Object 264

Opening New Windows 284

Security 298

Summary 298

Exercise Questions 299

Chapter 9: String Manipulation 301

Additional String Methods 302

Regular Expressions 306

The String Object — split(), replace(), search(), and match() Methods 327

Using the RegExp Object’s Constructor 335

Summary 345

Exercise Questions 345

Chapter 10: Date, Time, and Timers 347

World Time 348

Timers in a Web Page 358

Summary 364

Exercise Questions 365

Chapter 11: Storing Information: Cookies 367

Baking Your First Cookie 367

Creating a Cookie 377

Getting a Cookie’s Value 381

Cookie Limitations 386

Cookie Security and IE6+ 388

Summary 389

Exercise Questions 389

Chapter 12: Dynamic HTML and the W3C Document Object Model 391

The Web Standards 392

The Document Object Model 397

Manipulating the DOM 422

Writing Cross-Browser DHTML 447

JavaScript and XML 453

Summary 467

Exercise Questions 468

Chapter 13: Using ActiveX and Plug-Ins with JavaScript 469

Checking for and Embedding Plug-ins (Non-IE Browsers) 470

Checking for and Embedding ActiveX Controls on Internet Explorer 474

Using Plug-ins and ActiveX Controls 480

Summary 488

Exercise Question 489

Chapter 14: Ajax 491

What Is Ajax? 491

Using the XMLHttpRequest Object 494

Creating a Simple Ajax Module 500

Validating Form Fields with Ajax 505

Things to Watch Out For 515

Summary 525

Exercise Questions 525

Chapter 15: JavaScript Frameworks 527

Picking a Framework to Work With 527

Getting Started 528

Digging Deeper Into jQuery 537

Diving into Prototype 558

Delving into MooTools 575

Summary 590

Exercise Questions 590

Appendix A: Answers to Exercises 591

Appendix B: JavaScript Core Reference 665

Appendix C: W3C DOM Reference 697

Appendix D: Latin-1 Character Set 725

Index 733

Read More Show Less

First Chapter

Beginning JavaScript

By Paul Wilton

John Wiley & Sons

ISBN: 0-7645-5587-1

Chapter One

Introduction to JavaScript and the Web

In this introductory chapter, we'll take a look at what JavaScript is, what it can do for you, and what you need to be able to use it. With these foundations in place, we will see throughout the rest of the book how JavaScript can help you to create powerful web applications for your website.

The easiest way to learn something is by actually doing it, so throughout the book we'll be creating a number of useful example programs using JavaScript. We start this process in this chapter, by the end of which you will have created your first piece of JavaScript code.

Additionally over the course of the book, we'll develop a complete JavaScript web application: an online trivia quiz. By seeing it develop, step-by-step, you'll get a good understanding of how to create your own web applications. At the end of this chapter, we'll look at the finished trivia quiz and discuss the ideas behind its design.

Introduction to JavaScript

In this section, we're going to take a brief look at what JavaScript is, where it came from, how it works, and what sorts of useful things we can do with it.

What Is JavaScript?

Having bought this book you are probably already well aware that JavaScript is some sort of computer language, but what is a computer language? Put simply, a computer language is a series of instructions that instruct the computer to do something. That something can be a wide variety of things, including displaying text, moving an image, or asking the user for information. Normally the instructions, or what is termed code, are processed from the top line downward. Processed simply means that the computer looks at the code we've written, works out what action we want taken, and then takes that action. The actual act of processing the code is called running or executing it.

Using natural English, let's see what instructions, or code, we might write to make a cup of coffee.

1. Put coffee in cup.

2. Fill kettle with water.

3. Put kettle on to boil.

4. Has the kettle boiled? If so, then pour water into cup; otherwise, continue to wait.

5. Drink coffee.

We'd start running this code from the first line (instruction 1), and then continue to the next (instruction 2), then the next, and so on until we came to the end. This is pretty much how most computer languages work, JavaScript included. However, there are occasions when we might change the flow of execution, or even skip over some code, but we'll see more of this in Chapter 3.

JavaScript is an interpreted language, rather than a compiled language. What do we mean by the terms interpreted and compiled?

Well, to let you in on a secret, your computer doesn't really understand JavaScript at all. It needs something to interpret the JavaScript code and convert it into something that it understands; hence it is an interpreted language. Computers only understand machine code, which is essentially a string of binary numbers (that is, a string of zeros and ones). As the browser goes through the JavaScript, it passes it to a special program called an interpreter, which converts the JavaScript to the machine code your computer understands. It's a bit like having a translator to translate English into Spanish, for example. The important point to note is that the conversion of the JavaScript happens at the time the code is run; it has to be repeated every time the code is run. JavaScript is not the only interpreted language; there are others, including VBScript.

The alternative compiled language is one where the program code is converted to machine code before it's actually run, and this conversion only has to be done once. The programmer uses a compiler to convert the code that he wrote to machine code, and it is this machine code that is run by the program's user. Compiled languages include Visual Basic and C++. Using a real-world analogy, it's like having someone translate our English document into Spanish. Unless we change the document, we can use it without retranslation as much as we like.

Perhaps this is a good point to dispel a widespread myth: JavaScript is not the script version of the Java language. In fact, although they share the same name, that's virtually all they do share. Particularly good news is that JavaScript is much, much easier to learn and use than Java. In fact, languages like JavaScript are the easiest of all languages to learn but are still surprisingly powerful.

JavaScript and the Web

For most of this book we'll be looking at JavaScript code that runs inside a web page loaded into a browser. All we need to create these web pages is a text editor, for example, Windows NotePad, and a web browser, such as Netscape Navigator or Internet Explorer, with which we can view our pages. These browsers come equipped with JavaScript interpreters.

In fact, the JavaScript language first became available in the web browser Netscape Navigator 2. Initially, it was called LiveScript. However, because Java was the hot technology of the time, Netscape decided that JavaScript sounded more exciting. Once JavaScript really took off, Microsoft decided to add their own brand of JavaScript to Internet Explorer, which they named JScript. Since then, both Netscape and Microsoft have released improved versions and included them in their latest browsers. Although these different brands and versions of JavaScript have much in common, there are enough differences to cause problems if we're not careful. Initially we'll be creating code that'll work with Netscape and Microsoft version 4 and later browsers. Later chapters of the book look at features available only to Netscape 6+ and IE 5.5+. We'll look into the problems with different browsers and versions of JavaScript later in this chapter, and see how we deal with them.

The majority of the web pages containing JavaScript that we will create in this book can be stored on your hard drive and loaded directly into your browser from the hard drive itself, just as you'd load any normal file (such as a text file). However, this is not how web pages are loaded when we browse websites on the Internet. The Internet is really just one great big network connecting computers together. Websites are a special service provided by particular computers on the Internet; the computers providing this service are known as web servers.

Basically the job of a web server is to hold lots of web pages on its hard drive. When a browser, usually on a different computer, requests a web page that is contained on that web server, the web server loads it from its own hard drive and then passes the page back to the requesting computer via a special communications protocol called HyperText Transfer Protocol (HTTP). The computer running the web browser that makes the request is known as the client. Think of the client/server relationship as a bit like a customer/ shopkeeper relationship. The customer goes into a shop and says, "Give me one of those." The shopkeeper serves the customer by reaching for the item requested and passing it back to the customer. In a web situation, the client machine running the web browser is like the customer and the web server getting the page requested is like the shopkeeper.

When we type an address into the web browser, how does it know which web server to get the page from? Well, just as shops have addresses, say, 45 Central Avenue, SomeTownsville, so do web servers. Web servers don't have street names; instead they have Internet Protocol (IP) addresses, which uniquely identify them on the Internet. These consist of four sets of numbers, separated by dots; for example,

If you've ever surfed the net, you're probably wondering what on earth I'm talking about. Surely web servers have nice names, not IP addresses? In fact, the name is the "friendly" name for the actual IP address; it's a whole lot easier for us humans to remember. On the Internet, the friendly name is converted to the actual IP address by computers called domain name servers, something your Internet service provider will have set up for you.

Toward the end of the book, we'll go through the process of how to set up our own web server in a step-by-step guide. We'll see that web servers are not just dumb machines that pass pages back to clients, but in fact they can do a bit of processing themselves using JavaScript. We'll be looking at this later in the book as well.

Why Choose JavaScript?

JavaScript is not the only scripting language; there are others such as VBScript and Perl. So why choose JavaScript over the others?

The main reason for choosing JavaScript is its widespread use and availability. Both of the most commonly used browsers, Internet Explorer and Netscape Navigator, support JavaScript, as do some of the less commonly used browsers. So, basically we can assume that most people browsing our website will have a version of JavaScript installed, though it is possible to use a browser's options to disable it.

Of the other scripting languages we mentioned, VBScript, which can be used for the same purposes as JavaScript, is only supported by Internet Explorer running on the Windows operating system, and Perl is not used at all in web browsers.

JavaScript is also very versatile and not just limited to use within a web page. For example, it can be used in Windows to automate computer administration tasks and inside Adobe Acrobat.pdf files to control the display of the page just as in web pages, although this is a more limited version of JavaScript. However, the question of which scripting language is the most powerful and useful has no real answer. Pretty much everything that can be accomplished in JavaScript can be done in VBScript, and vice versa.

What Can JavaScript Do for Me?

The most common uses of JavaScript are interacting with users, getting information from them, and validating their actions. For example, say we want to put a drop-down menu on the page so that users can choose where they want to go to on our website. The drop-down menu might be plain old HTML, but it needs JavaScript behind it to actually do something with the user's input. Other examples of using JavaScript for interactions are given by forms, which are used for getting information from the user. Again these may be plain HTML, but we might want to check the validity of the information that the user is entering. For example, if we had a form taking a user's credit card details in preparation for the online purchase of goods, we'd want to make sure they had actually filled in their credit card details before we sent them the goods. We might also want to check that the data being entered is of the correct type, such as a number for their age rather than text.

JavaScript can also be used for various "tricks." One example is switching an image in a page for a different one when the user rolls her mouse over it, something often seen in web page menus. Also, if you've ever seen scrolling messages in the browser's status bar (usually at the bottom of the browser window) or inside the page itself and wondered how they manage that, this is another JavaScript trick that we'll demonstrate later in the book. We'll also see how to create expanding menus that display a list of choices when a user rolls his or her mouse over them, another commonly seen JavaScript-driven trick.

Tricks are OK up to a point, but even more useful are small applications that provide a real service. For example, a mortgage seller's website that has a JavaScript-driven mortgage calculator, or a website about financial planning that includes a calculator that works out your tax bill for you. With a little inventiveness you'll be amazed at what can be achieved.

Tools Needed to Create JavaScript Web Applications

All that you need to get started with creating JavaScript code for web applications is a simple text editor, such as Windows NotePad, or one of the many slightly more advanced text editors that provide line numbering, search and replace, and so on. An alternative is a proper HTML editor; you'll need one that allows you to edit the HTML source code, because that's where you need to add your JavaScript. A number of very good tools specifically aimed at developing web-based applications, such as Macromedia's excellent Dreamweaver MX, are also available. However, in this book we'll be concentrating on JavaScript, rather than any specific development tool. When it comes to learning the basics, it's often best to write the code by hand rather than relying on a tool to do it for you. This helps you to understand the fundamentals of the language before you attempt the more advanced logic that is beyond a tool's capability. Once you have a good understanding of the basics, you can use tools as timesavers so that you can spend more time on the more advanced and more interesting coding.

You'll also need a browser to view your web pages in. It's best to develop your JavaScript code on the sort of browsers you expect visitors to use to access your website. We'll see later in the chapter that there are different versions of JavaScript, each supported by different versions of the web browsers. Each of these JavaScript versions, while having a common core, also contains various extensions to the language. All the examples that we give in this book have been tested on Netscape Navigator versions 4.0, 4.7, 6, and 7, and Internet Explorer versions 4.0 to 6.0. Wherever a piece of code does not work on any of these browsers, a note to this effect has been made in the text. (In case you're wondering, Netscape Navigator 5 never made it out on general release to the public.)

Even if your browser supports JavaScript, it is possible to disable this functionality in the browser. So, before we start on our first JavaScript examples in the next section, you should check whether JavaScript is enabled in your browser.

To do this in Netscape Navigator, choose Preferences from the Edit menu on the browser. In the window that appears, click the Advanced tab or item from the list. In Netscape 7 you need to click on Scripts and plug-ins, and check that the checkbox beside Enable JavaScript for Navigator is checked. If not, then check it. You can also change what JavaScript code is permitted to do; for example, you can modify the code to permit JavaScript to open new browser windows.

It is harder to turn off scripting in Internet Explorer. Choose Internet Options from the Tools menu on the browser, click the Security tab, and check whether the Internet or Local intranet options have custom security settings. If either of them do, click the Custom Level button, and scroll down to the Scripting section. Check that Active Scripting is set to Enable.


Excerpted from Beginning JavaScript by Paul Wilton Excerpted by permission.
All rights reserved. No part of this excerpt may be reproduced or reprinted without permission in writing from the publisher.
Excerpts are provided by Dial-A-Book Inc. solely for the personal use of visitors to this web site.

Read More Show Less

Interviews & Essays

Author Questionnaire

1. What part of the book did you enjoy writing the most?

The chapter on regular expressions (String Manipulation) was quite fulfilling as it's something a lot of people seem to have problems with but often skipped over by many books. At the company I work for anything relating to regular expressions usually gets passed on to me, from now on hopefully I can refer them to a page in the book!!!

2. Now that you have seen book writing from two sides (as a main author with Beg JavaScript and one of many with Pro JavaScript), how do the two styles compare, and which did you prefer?

Overall I prefer being the main author as you get much more input into what goes into the book. Also I think its easier to make each chapter flow from one to the next when its just one author.

3. What did you want to achieve with the book?

My aim was a book filled with the sort of stuff that really is used in developing websites. I also wanted to make sure that the book provided the reader with a good understanding of both programming and JavaScript. Some books just provide lots of JavaScript "tricks" which the reader cuts and pastes into their web pages but don't provide the understanding of JavaScript that lets the reader go it alone and create their own programs.

4. How did you come up with the lovely Trivia Quiz example in the book?

One of the first programs I created for my very first website a long time ago was a trivia quiz. Admittedly it was not as powerful as the one in the book. Additionally the quiz includes a lot of the techniques used in practice, seems more fun than some applications and it would be very easy for the reader to develop the quiz further.

5. How did you first start learning JavaScript/what was the first piece of script you wrote?

A couple of months after first connecting to the Internet and looking at lots of websites I thought - "I can do that" so I did. My first website included all sorts of clever JavaScript tricks and was getting all of 3 visitors a year at its peak. I then realised that JavaScript is great for enhancing the user interface but does not replace content!!! However using JavaScript based applications to provide content has really helped boost numbers to my current websites, one of which is for alumni of Keele university and gets 50,000 hits a year, certainly up from the three of my first website.

6. What are your views on the new release of Netscape 6?

Its certainly a lot better than their version 4 browser. It does make it much easier to create websites that are compatible with Netscape 6 and Internet Explorer 5. On the downside Netscape 6's lack of backwards compatibility means we need to create not just IE and Netscape compatible websites but IE, Netscape and Netscape 6 websites.

7. Apart from writing splendid books, what do you like to do in your spare time?

Watching films and listening to music. If it wasn't for my lack of talent I'd like to be the next Tarantino.

Courtesy for Wrox Press

Read More Show Less

Customer Reviews

Average Rating 5
( 2 )
Rating Distribution

5 Star


4 Star


3 Star


2 Star


1 Star


Your Rating:

Your Name: Create a Pen Name or

Barnes & Review Rules

Our reader reviews allow you to share your comments on titles you liked, or didn't, with others. By submitting an online review, you are representing to Barnes & that all information contained in your review is original and accurate in all respects, and that the submission of such content by you and the posting of such content by Barnes & does not and will not violate the rights of any third party. Please follow the rules below to help ensure that your review can be posted.

Reviews by Our Customers Under the Age of 13

We highly value and respect everyone's opinion concerning the titles we offer. However, we cannot allow persons under the age of 13 to have accounts at or to post customer reviews. Please see our Terms of Use for more details.

What to exclude from your review:

Please do not write about reviews, commentary, or information posted on the product page. If you see any errors in the information on the product page, please send us an email.

Reviews should not contain any of the following:

  • - HTML tags, profanity, obscenities, vulgarities, or comments that defame anyone
  • - Time-sensitive information such as tour dates, signings, lectures, etc.
  • - Single-word reviews. Other people will read your review to discover why you liked or didn't like the title. Be descriptive.
  • - Comments focusing on the author or that may ruin the ending for others
  • - Phone numbers, addresses, URLs
  • - Pricing and availability information or alternative ordering information
  • - Advertisements or commercial solicitation


  • - By submitting a review, you grant to Barnes & and its sublicensees the royalty-free, perpetual, irrevocable right and license to use the review in accordance with the Barnes & Terms of Use.
  • - Barnes & reserves the right not to post any review -- particularly those that do not follow the terms and conditions of these Rules. Barnes & also reserves the right to remove any review at any time without notice.
  • - See Terms of Use for other conditions and disclaimers.
Search for Products You'd Like to Recommend

Recommend other products that relate to your review. Just search for them below and share!

Create a Pen Name

Your Pen Name is your unique identity on It will appear on the reviews you write and other website activities. Your Pen Name cannot be edited, changed or deleted once submitted.

Your Pen Name can be any combination of alphanumeric characters (plus - and _), and must be at least two characters long.

Continue Anonymously
Sort by: Showing all of 3 Customer Reviews
  • Anonymous

    Posted January 19, 2001

    Excellent book for all levels of experience

    This excellent book manages to be very in-depth but without losing clarity or containing unneccessary detail. Although an excellent tutor the book also makes for a good reference manual of techniques. I've done some JavaScripting before but was uncertain about things like scripting between frames but that was covered in-depth. As a new book its obiously very uptodate, in particular its coverage of Netscape 6.

    2 out of 2 people found this review helpful.

    Was this review helpful? Yes  No   Report this review
  • Anonymous

    Posted February 26, 2001

    An excellant JavaScript book!

    Paul Wilton has done a great job guiding readers from the basics to the advanced concepts with thorough illustrations and explanations. It provides updated references at the back of the book as well. I used to 'cut and paste' other people's JavaScript codes, now after reading this book, I am ready to start writing my own codes.

    2 out of 2 people found this review helpful.

    Was this review helpful? Yes  No   Report this review
  • Posted October 21, 2008

    I Also Recommend:

    Good, but supposedly incomplete.

    This was a textbook I used as a student at a community college. I thought it was good, although the teacher claimed it was missing basics about form validation. The teacher recommended instead: "Javascript : The Complete Reference" by Thomas Powell and Fritz Schneider, which is the same price, but I can't vouch for that recommended book's readability / understandability since I never looked at it in detail. This reviewed book touched on a lot of topics I had been wanting to learn, and it described them in an understandable way, such as CSS, DOM, DHTML, XML, Ajax, plug-ins, nuances of increment operators like in ++i, and there is nice coverage of cookies. The book was invaluable to me at one point because it explained why our computer at work kept throwing up JavaScript errors in such profusion that the PC became virtually unusable, and the book showed how to disable those error messages, which made our PC usable again. A lady in our class had the same problem with her home computer, and that was one of her first questions when the class started. The book's warning about wrong use of the length function also allowed me to detect an error in an online test I was given as employment prescreening. One minor complaint I have about this book is that acronyms and definitions are not collected into one place, and some acronyms like XSLT, IIS, MSXML, MSIE, and ASP are never defined, though I already knew some of them, or else they were easy enough to guess. There were a few typographical errors I spotted in English sentences. The book had good insights into cross-browser compatibility, and I never realized until reading this book how much work JavaScript programmers had to do to ensure such compatibility. The chapter on Common Mistakes was a great idea, though I would have preferred to see a longer list, and to have it laid out in order, based on statistics of how often those errors are encountered by neophytes.

    1 out of 1 people found this review helpful.

    Was this review helpful? Yes  No   Report this review
Sort by: Showing all of 3 Customer Reviews

If you find inappropriate content, please report it to Barnes & Noble
Why is this product inappropriate?
Comments (optional)