Back to description
In this introductory chapter, you look at what JavaScript is, what it can do for you, and what you need in order to use... more
In this introductory chapter, you look at what JavaScript is, what it can do for you, and what you need in order to use it. With these foundations in place, you will see throughout the rest of the book how JavaScript can help you to create powerful web applications for your web site.
The easiest way to learn something is by actually doing it, so throughout the book you'll create a number of useful example programs using JavaScript. This process starts 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 you'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, you'll look at the finished trivia quiz and consider the ideas behind its design.
... less
One of the main uses of computers is to process and display information. By processing, we mean that the information is... more
One of the main uses of computers is to process and display information. By processing, we mean that the information is modified, interpreted, or filtered in some way by the computer. For example, on an online banking web site, a customer may request details of all moneys paid out from his account in the last month. Here the computer would retrieve the information, filter out any information not related to payments made in the last month, and then display what's left in a web page. In some situations, information is processed without being displayed, and at other times, information is obtained directly without being processed. For example, in a banking environment, regular payments may be processed and transferred electronically without any human interaction or display.
In computing we refer to information as data. Data come in all sorts of forms, such as numbers, text, dates, and times, to mention just a few. In this chapter, you look specifically at how JavaScript handles data such as numbers and text. An understanding of how data are handled is fundamental to any programming language.
The chapter starts by looking at the various types of data JavaScript can process. Then you look at how you can store these data in the computer's memory so you can use them again and again in the code. Finally, you see how to use JavaScript to manipulate and process the data.
So far, you've seen how to use JavaScript to get user input, perform calculations and tasks with that input,... more
So far, you've seen how to use JavaScript to get user input, perform calculations and tasks with that input, and write the results to a web page. However, a pocket calculator can do all this, so what is it that makes computers different? That is to say, what gives computers the appearance of having intelligence? The answer is the capability to make decisions based on information gathered.
How will decision-making help you in creating web sites? In the last chapter you wrote some code that converted temperature in degrees Fahrenheit to centigrade. You obtained the degrees Fahrenheit from the user using the prompt() function. This worked fine if the user entered a valid number, such as 50. If, however, the user entered something invalid for the Fahrenheit temperature, such as the string aaa, you would find that your code no longer works as expected. Now, if you had some decision-making capabilities in your program, you could check to see if what the user has entered is valid. If it is, you can do the calculation, and if it isn't, you can tell the user why and ask him to enter a valid number.
prompt()
50
aaa
Validation of user input is probably one of the most common uses of decision making in JavaScript, but it's far from being the only use. The trivia quiz also needs some decision-making capabilities so that you can check if the answer given by the user is right or wrong. If it's right, you need to take certain steps, such as telling the user that she is right and increasing her score. If the answer is wrong, a different set of code needs to be executed to tell her that she’s wrong.
In this chapter you'll look at how decision making is implemented in JavaScript and how you can use it to make your code smarter.
JavaScriptAn Object-Based Language
In this chapter, you look at a concept that is central to JavaScript,... more
In this chapter, you look at a concept that is central to JavaScript, namely objects. But what are objects, and why are they useful?
First, we have to break it to you: You have been using objects throughout this book (for example, an array is an object). JavaScript is an object-based language, and therefore much of what you do involves manipulating objects. You'll see that when you make full use of these objects, the range of things you can do with JavaScript expands immensely.
We'll start this chapter by taking a look at the idea of what objects are and why they are important. We'll move on to what kinds of objects are used in JavaScript, how to create them and use them, and how they simplify many programming tasks for you. Finally, you'll see in more detail some of the most useful objects that JavaScript provides and how to use these in practical situations.
Not only does JavaScript itself consist of a number of these things called objects (which are also called native JavaScript objects), but also the browser itself is modeled as a collection of objects available for your use. You'll learn about these objects in particular in the next chapter.
Over the past three chapters, you've examined the core JavaScript language. You've seen how to work with variables and... more
Over the past three chapters, you've examined the core JavaScript language. You've seen how to work with variables and data, perform operations on those data, make decisions in your code, loop repeatedly over the same section of code, and even how to write your own functions. In the preceding chapter you moved on to learn how JavaScript is an object-based language, and you saw how to work with the native JavaScript objects. However, you are not interested only in the language itselfyou want to find out how to write script for the web browser. Using this ability, you can start to create more impressive web pages.
Not only is JavaScript object-based, but the browser is also made up of objects. When JavaScript is running in the browser, you can access the browser's objects in exactly the same way that you used JavaScript's native objects in the last chapter. But what kinds of objects does the browser provide?
The browser makes available a remarkable number of objects. For example, there is a window object corresponding to the window of the browser. You have already been using two methods of this object, namely the alert() and prompt() methods. For simplicity, we previously referred to these as functions, but they are in fact methods of the browser's window object.
window
alert()
Another object made available by the browser is the page itself, represented by the document object. Again, you have already used methods and properties of this object. Recall from Chapter 1 that you used the document object's bgColor property to change the background color of the page. You have also been using the write() method of the document object to write information to the page.
document
bgColor
write()
A variety of other objects exist, representing a lot of the HTML that you write in the page. For example, there is an img object for each <img> tag that you use to insert an image into your document.
img
<img>
The collection of objects that the browser makes available to you for use with JavaScript is generally called the Browser Object Model (BOM).
You will often see this termed the Document Object Model (DOM). However, throughout this book, we'll use the term DOM to refer to the W3C's standard Document Object Model, which is discussed in Chapter 13.
All this added functionality of JavaScript comes with a potential downside. Which collections of objects are made available to you is highly dependent on the brand and version of the browser that you are using. Some objects are made available in some browsers and not in others, whereas other objects have different properties and methods in different browsers. The good news is that browsers are following the W3C's guidelines much more than they used to. This means that if you follow the W3C guidelines, your code is more likely to work with different browsers. Note, however, some browser writers have interpreted the W3C standards in a different way. You will see much more about the differences between the BOMs of IE and Firefox browsers in Chapter 12.
However, in this chapter you will concentrate on the core functionality of the BOM, the objects that are common to all browsers. You can achieve a lot in JavaScript by just sticking to such objects. You can find more information on them online at http://www.w3schools.com/dhtml/dhtml_domreference.asp and http://msdn.microsoft.com/library/default.asp?url=/workshop/author/dhtml/dhtml_node_entry.asp.
http://www.w3schools.com/dhtml/dhtml_domreference.asp
http://msdn.microsoft.com/library/default.asp?url=/workshop/author/dhtml/dhtml_node_entry.asp
Web pages would be very boring if you could not interact with or obtain information from the user,... more
Web pages would be very boring if you could not interact with or obtain information from the user, such as text, numbers, or dates. Luckily, with JavaScript this is possible. You can use this information within the web page, or it can be posted to the web server where you can manipulate it and store it in a database if you wish. In this chapter you'll concentrate on using the information within the web browser, which is called client-side processing. In Chapters 14 and 15 you'll see how to send this information to a web server and store it in a database, which is called server-side processing.
You're quite accustomed to various user interface elements. For example, the Windows operating system has a number of standard elements, such as buttons you can click; lists, drop-down list boxes, and radio buttons you can select from; and boxes you can check. The same applies with any graphical user interface (GUI) operating system, whether it's a Mac, Unix, or Linux system. These elements are the means by which we now interface with applications. The good news is that you can include many of these types of elements in your web pageand even better, it's very easy to do so. When you have such an elementsay, a buttoninside your page, you can then tie code to its events. For example, when the button is clicked, you can fire off a JavaScript function you've created.
It's important to note at this point that the elements we discuss in this chapter are the common elements made available by HTML, and not ActiveX elements, Java Applets, or plug-ins. You'll look at some of these in Chapter 15.
All of the HTML elements used for interaction should be placed inside an HTML form. In Netscape 4+, it’s compulsory for the elements to be inside a form; otherwise they won't be displayed. It’s also compulsory if you submit the form to a server. Let's start by taking a look at HTML forms and how you interact with them in JavaScript.
Until now, the pages you have been looking at have just been single pages. However, many web applications make use of... more
Until now, the pages you have been looking at have just been single pages. However, many web applications make use of frames to split up the browser's window, much as panes of glass split up a real window. It's quite possible that you'll want to build web sites that make use of such frames. The good news is that JavaScript enables the manipulation of frames and allows functions and variables you create in one frame to be used from another frame. One advantage of this is that you can keep common variables and functions in one place but use them from many places. You start this chapter by looking at how you can script across such frames.
But a number of other good reasons exist for wanting to access variables and functions in another frame. Two important reasons are to make your code modular and to gain the ability to maintain information between pages.
What do we mean by modular? In other programming languages, like Visual Basic, you can create a modulean area to hold general functions and variablesand reuse it from different places in your program. Well, when using frames you can put all of your general functions and variables into one area, such as the top frame, which you can think of as your code module. Then you can call the functions repeatedly from different pages and different frames.
If you put the general functions and variables in a page that defines the frames that it contains (that is, a frameset-defining page), then if you need to make changes to the pages inside the frames, any variables defined in the frameset page will retain their value. This provides a very useful means of holding information even when the user is navigating your web site. A further advantage is that any functions defined in the frameset-defining page can be called by subsequent pages and have to be loaded into the browser only once, making your page's loading faster.
The second subject of this chapter is how you can open up and manipulate new browser windows. There are plenty of good uses for new windows. For example, you may wish to open up an “external” web site in a new window from your web site, but still leave your web site open for the user. External here means a web site created and maintained by another person or company. Let’s say you have a web site about carswell, you may wish to have a link to external sites, such as manufacturing web sites (for example, that of Ford or General Motors). Perhaps even more useful is using small windows as dialog boxes, which you can use to obtain information from the user. Just as you can script between frames, you can do similar things between certain windows. You find out how later in the chapter, but let's start by looking at scripting between frames.
In Chapter 4 you looked at the String object, which is one of the native objects that JavaScript makes available to... more
String
In Chapter 4 you looked at the String object, which is one of the native objects that JavaScript makes available to you. You saw a number of its properties and methods, including the following:
lengthThe length of the string in characters
length
charAt() and charCodeAt()The methods for returning the character or character code at a certain position in the string
charAt()
charCodeAt()
indexOf() and lastIndexOf()The methods that allow you to search a string for the existence of another string and that return the character position of the string if found
indexOf()
lastIndexOf()
substr() and substring()The methods that return just a portion of a string
substr()
substring()
toUpperCase() and toLowerCase()The methods that return a string converted to upper- or lowercase
toUpperCase()
toLowerCase()
In this chapter you'll look at four new methods of the String object, namely split(), match(), replace(), and search(). The last three, in particular, give you some very powerful text-manipulation functionality. However, to make full use of this functionality, you need to learn about a slightly more complex subject.
split()
match()
replace()
search()
The methods split(), match(), replace(), and search() can all make use of regular expressions, something JavaScript wraps up in an object called the RegExp object. Regular expressions enable you to define a pattern of characters, which can be used for text searching or replacement. Say, for example, that you have a string in which you want to replace all single quotes enclosing text with double quotes. This may seem easyjust search the string for ' and replace it with "but what if the string is Bob O'Hara said "Hello"? You would not want to replace the single-quote character in O'Hara. You can perform this text replacement without regular expressions, but it would take more than the two lines of code needed if you do use regular expressions.
,
RegExp
'
"
Bob O'Hara said "Hello"
single-quote character
O'Hara
Although split(), match(), replace(), and search() are at their most powerful with regular expressions, they can also be used with just plain text. You'll take a look at how they work in this simpler context first, to become familiar with the methods.
In Chapter 4 we discuss that the concepts of date and time are embodied in JavaScript through the Date... more
Date
In Chapter 4 we discuss that the concepts of date and time are embodied in JavaScript through the Date object. You looked at some of the properties and methods of the Date object, including the following:
The methods getDate(), getDay(), getMonth(), and getFullYear() enable you to retrieve date values from inside a Date object.
getDate()
getDay()
getMonth()
getFullYear()
The setDate(), setMonth(), and setFullYear() methods enable you to set the date values of an existing Date object.
setDate()
setMonth()
setFullYear()
The getHours(), getMinutes(), getSeconds(), and getMilliseconds() methods retrieve the time values in a Date object.
getHours()
getMinutes()
getSeconds()
getMilliseconds()
The setHours(), setMinutes(), setSeconds(), and setMilliseconds() methods enable you to set the time values of an existing Date object.
setHours()
setMinutes()
setSeconds()
setMilliseconds()
One thing not covered in that chapter was the idea that the time depends on your location around the world. In this chapter you'll be correcting that omission by looking at date and time in relation to world time.
For example, imagine you have a chat room on your web site and want to organize a chat for a certain date and time. Simply stating 15:30 is not good enough if your web site attracts international visitors. The time 15:30 could be Eastern Standard Time, Pacific Standard Time, the time in the United Kingdom, or even the time in Kuala Lumpur. You could of course say 15:30 EST and let your visitors work out what that means, but even that isn't foolproof. There is an EST in Australia as well as in the United States. Wouldn't it be great if you could automatically convert the time to the user's time zone? In this chapter you'll see how.
As well as looking at world time, you'll also be looking at how to create a timer in a web page. You'll see that by using the timer you can trigger code, either at regular intervals or just once (for example, five seconds after the page has loaded). You'll see how you can use timers to add a real-time clock to a web page and how to create scrolling text in the status bar. Timers can also be useful for creating animations or special effects in your web applications. Finally, you'll be using the timer to enable the users of your trivia quiz to give themselves a time limit for answering the questions.
Even a JavaScript guru makes mistakes, even if they are just annoying typos. In particular, when code expands to hundreds... more
Even a JavaScript guru makes mistakes, even if they are just annoying typos. In particular, when code expands to hundreds of lines, the chance of something going wrong becomes much greater. In proportion, the difficulty in finding these mistakes, or bugs, also increases. In this chapter you will look at various techniques that will help you minimize the problems that arise from this situation.
You'll start by taking a look at the top seven JavaScript coding mistakes. After you know what they are, you’ll be able to look out for them when writing code. Hopefully, so that you won't make them so often!
Then you'll look at the Microsoft script debugger, which can be used with Internet Explorer. You'll see how you can use it to step through your code and check the contents of variables while the code is running, a process that enables us to hunt for difficult bugs. You'll also take a briefer look at the debugging tools available for Firefox.
Finally, you'll look at how you can cope with errors when they do happen, so that you prevent users from seeing your coding mistakes.
Our goal as web site programmers should be to make the web site experience as easy and pleasant for the user as possible.... more
Our goal as web site programmers should be to make the web site experience as easy and pleasant for the user as possible. Clearly, well-designed pages with easily navigable layouts are central to this, but they're not the whole story. You can go one step further by learning about your users and using information gained about them to personalize the web site.
For example, imagine a user, whose name you asked on the first visit, returns to your web site. You could welcome her back to the web site by greeting her by name. Another good example is given by a web site, such as Amazon's, that incorporates the one-click purchasing system. By already knowing the user's purchasing details, such as credit-card number and delivery address, you can allow the user to go from viewing a book to buying it in just one click, making the likelihood of the user purchasing it that much greater. Also, based on information, such as the previous purchases and browsing patterns of the user, it's possible to make book suggestions.
Such personalization requires that information about users be stored somewhere in between their visits to the web site. Previous chapters have mentioned that accessing the user's local file system from a web application is pretty much off limits because of security restrictions included in browsers. However, you, as a web site developer, can store small amounts of information in a special place on the user's local disk, using what is called a cookie. There may be a logical reason why they are named cookies, but it also provides authors with the opportunity to make a lot of second-rate, food-related jokes!
Dynamic HTML (DHTML) is a term with various meanings, but it can boiled down to one basic concept:... more
Dynamic HTML (DHTML) is a term with various meanings, but it can boiled down to one basic concept: dynamically changing a web page after it is loaded into the browser. For example, it can be used to change the color and style of text when the mouse pointer moves over it. It is also widely used to enhance the experience a visitor has when visiting a web page, making the page more interactive.
Before the advent of DHTML, web pages were static. That is, when an HTML document was downloaded and displayed in the user's browser, no changes could be made to the page's content or appearance. With DHTML, however, you can change the appearance of the existing content and even move content around on the screen. Want to change that heading color to red? No problemo. Want to make text scroll across the screen? You got it.
JavaScript provides you with a means of writing DHTML pages. You've already seen this in action with the example in Chapter 5 in which you enabled the user to change an image loaded into the page with the click of a button. Today's browsers go beyond this, and you can change virtually anything in a web page.
In this chapter, you’ll take an introductory look at DHTML. You’ll look at how you can change things and move things around on the page. At the end of the chapter, you’ll build a scrolling marquee to display whatever text you desire.
In the last chapter you were introduced to DHTML, getting a small glimpse of what it can do with a scrolling text animation.... more
In the last chapter you were introduced to DHTML, getting a small glimpse of what it can do with a scrolling text animation. You also saw that web developers need to use different code for different browsers to achieve the same results, which makes their lives difficult. In this chapter you’ll be concentrating on writing code according to the web standards set by the W3C. In general, you can write code that will work with IE 6+, Firefox, Opera, and Safari without having to make big changes.
One of the most misunderstood sections in the W3C Web standards is the Document Object Model, or DOM for short. The DOM gives developers a way of representing everything on a web page so that it is accessible via a common set of properties and methods in JavaScript, or any other object-based programming language. By everything, we mean everything. You can change the graphics, tables, forms, and even text itself by altering a relevant DOM property with JavaScript.
The DOM should not be confused with the Browser Object Model (BOM) that was introduced in Chapter 5. You'll see the differences between the two in detail shortly. For now, though, think of the BOM as a browser-dependent representation of every feature of the browser, from the browser buttons, URL address line, and title bar to the browser window controls, as well as parts of the web page, too. The DOM, however, deals only with the contents of the browser window or web pagein other words, the HTML document. It makes the document available in such a way that any browser can use exactly the same code to access and manipulate the content of the document. To summarize, the BOM gives you access to the browser and some of the document, whereas the DOM gives you access to all of the document, but only the document.
The great thing about the DOM is that it is browser- and platform-independent. This means that developers can finally consider the possibility of writing a piece of JavaScript code that dynamically updates the page, as you saw in the last chapter, and that will work on any DOM-compliant browser without any tweaking. You should not need to code for different browsers or take excessive care when coding.
The DOM achieves this independence by representing the contents of the page as a generic tree structure. Whereas in the BOM you might expect to access something by looking up a property relevant to that part of the browser and adjusting it, the DOM requires navigation through its representation of the page through nodes and properties that are not specific to the browser. You'll explore this structure a little later.
However, to use the DOM standard, ultimately developers require browsers that completely implement the standard, something that no browser does 100 percent efficiently. Unfortunately, IE 5.5 didn’t support many aspects of the standard. IE 6 and 7 have greatly improved standards support, but still fall short of full implementation. Even Firefox, which at least aims to support the standard, still falls short in some ways.
This makes the DOM sound like an impossible ideal, yet it doesn't exist purely as a standard. Features of the DOM standard have been implemented in browsers as far back as Netscape 2. However, in Netscape versions 2, 3, and 4, many HTML page elements and their properties were not scriptable at allwhereas, as you have seen, IE made nearly all page elements and their properties scriptable. Unfortunately, the way in which Netscape 4 provided scripting access to some elements was often incompatible with the way in which IE made those elements available. Thus a Document Object Model standard was developed. The latest versions of IE, Mozilla, Opera, and Safari support many features outlined in the standard.
To provide a true perspective on how the DOM fits in, we need to take a brief look at its relationship with some of the other currently existing web standards. We should also talk about why there is more than one version of the DOM standard, and why there are different sections within the standard itself. (Microsoft, in particular, added a number of extensions to the W3C DOM.) After understanding the relationships, you can look at using JavaScript to navigate the DOM and to dynamically change content on web pages in more than one browser, in a way that used to be impossible with pure DHTML. The following items are on your agenda:
The HTML, ECMAScript, XML, and XHTML web standards
The DOM standards
The DOM tree structure
Writing cross-browser DHTML
Remember that the examples within this chapter are targeted only at the DOM and therefore will be supported only by IE 6+, FF 1+, Opera, and Safari.
In the previous chapter you took a brief look at Extensible Markup Language (XML). Like HTML, it consists of elements.... more
In the previous chapter you took a brief look at Extensible Markup Language (XML). Like HTML, it consists of elements. You saw that its purpose was to describe data rather than to actually display information in any particular format, which is the purpose of HTML. There is nothing special about XML. It is just plain text with the addition of some XML tags enclosed in angle brackets. You can use any software that can handle plain text to create and edit XML.
In this chapter you’ll be covering the fundamentals of XML. It’s a huge topic and deserves a whole book to do it justice, so this’ll be a taster to get you started. Before you get down to coding, let’s look at what XML can be used for.
Today's browsers provide a lot of built-in functionality; however, there are many things they cannot do unaided,... more
Today's browsers provide a lot of built-in functionality; however, there are many things they cannot do unaided, such as playing video or sound. Functionality of this sort has become quite common on the Internet, and it is thanks to plug-ins and their ability to extend browser functionality.
Plug-ins are applications that are downloaded and, as their name suggests, "plugged into" the browser. Many different plug-ins exist today; the more common ones include Adobe Flash Player, which plays Flash movies, and RealNetworks' Real Audio and video player, which plays real audio and media files.
Essentially, plug-ins are objects that encapsulate all the functionality they need to perform their tasks, such as playing audio files, in a way that hides the complexity from the programmer. They are usually written in languages such as C++ and Java.
Since its inception, the Internet has used a transaction-like communication model. A browser sends a request to a server,... more
Since its inception, the Internet has used a transaction-like communication model. A browser sends a request to a server, which sends a response to the browser, on which it (re)loads the page. This is typical HTTP communication, and it was designed to be this way, but this model is rather cumbersome for developers, as it requires our web applications to consist of several pages. The resulting user experience is disjointed and interrupted.
In the early 2000s, a movement began to look for and develop new techniques to enhance the user's experience, as well as make applications easier to build and maintain. These new techniques offered performance and usability usually associated with conventional desktop applications. It wasn't long before developers began to refine these processes to offer richer functionality.
At the heart of this movement was one language: JavaScript, and its remote scripting ability.
In this appendix you’ll find some suggested solutions to the exercise questions that appear at the end of most of... more
In this appendix you’ll find some suggested solutions to the exercise questions that appear at the end of most of the chapters in this book.
Purchase Before purchasing this product, please be sure you have met all software and system requirements, and that you understand any limits placed upon its use.
Return Policy Wrox Chapters on Demand are non-returnable and non-refundable.
Reader Software Wrox Chapters on Demand are offered as PDFs, and they must be viewed using the Adobe Reader. If you do not have the Reader installed, it can be downloaded for free at Adobe.com.
Test Download As Wrox Chapters on Demand purchases are non-returnable, it is advisable that you test your system and software configurations with a free sample download before you place an order.
Usage Rights for a Wrox Chapter on Demand File Any Wrox Chapter on Demand product you purchase from this site will come with certain restrictions that allow Wiley to protect the copyrights of its products. After you purchase and download this title, you:
If you have any questions about these restrictions, you may contact Customer Care at (877) 762-2974 (8 a.m. - 5 p.m. EST, Monday - Friday). If you have any issues related to Technical Support, please contact us at 800-762-2974 (United States only) or 317-572-3994 (International) 8 a.m. - 8 p.m. EST, Monday - Friday).
Related Books
Java Resources