java script

Introduction to JavaScript

Like many technologies that have enjoyed success and sticking power, JavaScript has taken
on new purpose and relevance since its creation many years ago. It ’ s no longer correct to say that
JavaScript is just a scripting language or even just for the web.
In fact, JavaScript is one of the few
truly multi - vendor, multi - platform, and multi - purpose programming languages in use today. It
holds this status not just because it happened to be the language that was designed for browser
scripting but also because it ’ s an extremely flexible, expressive, and forgiving language that both
amateurs and professional developers alike can appreciate. Certainly one could say it ’ s thanks to
the web that we have such an interesting and powerful way to build applications, but it ’ s thanks
to JavaScript that we have such an interesting and powerful web.

This book will serve as a detailed reference for all things JavaScript. This includes, of course, all the
language basics but also virtually everything to do with its core objects, features, and limitations.
You ’ ll examine advanced topics too, such as how JavaScript can be applied to provide specific
interactivity or features inside a web page, how to use it to manipulate the structure of web
documents, and how to interact with other web technologies like Flash, Silverlight, CSS, and even
offline storage.

This chapter will provide an overview of the language and how it fits into the spectrum of web
technologies. It ’ ll provide some insight as to how someone typically learns the language and will
explain both the history and current role of JavaScript amidst the cloud of competing browsers and
interpreters. Finally, I ’ ll introduce a simple web - based application using JavaScript and explain
how it all fits together.

JavaScript History

Beginning its life as a decidedly curious enhancement to Netscape called Mocha (an homage to
Java), JavaScript was intended for sparing use to add minor enhancements to the behavior of web
pages, primarily to web forms. Netscape and Sun Microsystems evidently believed that this new
dimensionality of the web could not, or should not, be addressed in the already complex
declarative syntax of HTML. Instead, a scripting language was born that would continue to breathe
life into the Internet for over a decade.
Before its full release, the name was changed to LiveScript and later to JavaScript . In March 1996,

Netscape
2.0 was released to the world with the first official version the language. By August of the same year,
Microsoft had released Internet Explorer 3.0 with a similar feature called JScript (but with some minor
improvements). Over the coming years, the two companies would move virtually neck and neck with
enhancements to the language. By June 1997, the international standards body Ecma approved a
submission by Netscape to standardize the language. This standardized version of the language would
be known as ECMAScript (ECMA - 262) and was revised four times between 1997 and 2009. To this day
there is some confusion in the developer community as to how “ JavaScript, ” “ ECMAScript, ” and
“ JScript ” differ. The simple answer is that ECMAScript refers to the published and standardized version
of the language, and JavaScript and JScript are dialects (or implementations) of that standard. Still, like
other genericized brands that came before it such as Kleenex, Frisbee, Q - Tip, and Band - Aid, the
JavaScript name stuck and probably always will.

Few programming languages have been as misunderstood as JavaScript. The root cause probably begins
with the misleading name. JavaScript has very little to do with Java the language or even the Java
Applet, another popular platform for web development in the early days. Compared to either, JavaScript
was much smaller, simpler, and more purpose - built. Developers who wanted to use some of the more
powerful features of Java in their JavaScript applications, such as class - based inheritance, were quickly
confronted with these differences. In the years that followed the initial launch, the mood toward browser
scripting swung wildly from enthusiasm to total distrust but recently to a place of high regard and rapid
adoption. In the intervening years, a lot was added to the core language, and implicit cooperation
between warring vendors like Microsoft and Mozilla allowed developers to write more to a single
standard for the most part, irrespective of which browser people might be using.

Of course, JavaScript is no longer limited for use inside web pages. After being Ecma standardized, it
was implemented as the scripting language of many other technologies like Flash, Adobe Acrobat,
Microsoft .NET, and even as a way to write desktop widgets. In fact, the Ecma standard has undergone
so many revisions in such a short period that the browser vendors no longer try to keep up, nor do they
all agree what direction it ’ s headed. While there are now many flavors of the language in a number of
contexts, this book approaches the language from a position of practical use primarily as a way to script
web pages. We have documented, as thoroughly as possible, where the core language leaves off and
uniqueness of the browser picks up. In the appendices at the end of this book, you will find a detailed
reference of the core language, how this maps to the Ecma standard, and also many of the browser
extensions that have been added by individual vendors like Microsoft and Mozilla.

ActionScript and Flash
Introduced in Macromedia Flash Player 5, ActionScript was an improvement on a scripting
feature introduced into Flash much earlier. The idea was simply to allow developers to apply custom
movements and behaviors based on user input. It was a full implementation of ECMAScript V1 and
allowed for both procedural and object oriented development styles. Around the time Adobe acquired
Macromedia, ActionScript 2.0 was released, which implemented ECMAScript working draft V4. It was
anticipated that the browser vendors would eventually follow - suit and implement this version also.
Unfortunately, subsequent political disputes between Microsoft and the Mozilla Foundation severely
reduced the likelihood that this version would ever be adopted universally, making Adobe one of the
few vendors likely to ever implement this particular branch of the language. Today, ActionScript is
implemented in both Flash and Flex and has a huge following of professional developers.

Adobe Integrated Runtime (AIR)
Adobe Integrated Runtime (AIR) is a relatively new offering from Adobe, but is already an important
fixture in the programming landscape. It offers cross - platform write - once, run anywhere desktop
development with a special focus on ease of integration with web services. Developers can write
applications in Flex or in HTML with JavaScript that can be compiled to run on OSX, Windows, or Linux
desktops. The HTML / JavaScript implementation is achieved by repackaging a custom version of
Webkit (Safari) with some API extensions to add features like online/offline detection, permanent SQLite
storage, and multimedia support.
In Other Adobe Products
Adobe has also implemented JavaScript as the language used to script and customize products such as
Dreamweaver (for making plugins), Acrobat (for customizing interfaces), and InDesign.

Desktop Widgets
With the popularization of Apple Dashboard widgets, Konfabulator widgets from Yahoo, and
Microsoft Gadgets for Vista, it ’ s now clear that JavaScript is the language of choice for desktop and
dashboard - type gadgets. A widget can be an egg timer, a news reader, or even a simple game. In each of
these cases, widgets can be generally constructed using a combination of JavaScript, CSS, HTML, and/
or XML. Depending on the platform, they may have some limited access to system resources (like the
file system), but generally they run in the context of a very small webpage. Apple Dashboard widgets
have the added capability of using Canvas (graphical) elements because they are rendered using Safari ’ s
browser engine WebKit.

Complementary Technologies
In the world of browser scripting in particular is a set of complementary technologies that developers
must understand. In this book, I will refer to these a great deal and you will develop a thorough
understanding of how they fit into the development stack and how developers can use them in their
applications to build powerful interfaces.

Hypertext Markup Language (HTML)
The declarative document markup language that makes up a web page interacts extensively with
JavaScript. Script allows us to make the page dynamic by writing new contents, and modifying existing
contents. You can interact with HTML by treating it as a big string and working with all the words and
symbols that make it up (as in the second example below), or by using the DOM (Document Object
Model) to manipulate the page in a hierarchical object - based way. Using HTML, you can tell the browser
to execute a block of script inline with the page using the following syntax:

< html >
< head >
< script type=”text/javascript” >
// This JavaScript block will execute first
< /script >
< /head >
< body >
< script type=”text/javascript” >
// This block will execute second
< /script >
< h1 > Hello World < /h1 >
< script type=”text/javascript” >
// This block will execute last
< /script >
< /body >
< /html >
You can also use JavaScript to generate HTML by simply writing it to the page:
< html >
< body >
< script >
document.write(“ < h1 > Hello world! < /h1 > ”);
< /script >
< /body >
< /html >

Cascading Style Sheets (CSS)

CSS describes the color, size, position, and shape of most things on a web page. CSS documents can
statically describe the look and feel of a document, but these attributes can also be changed after the
page has loaded. There is an in - depth object model available to script developers who wish to use it to
dynamically modify these attributes on the fly. By manipulating the style of an element with script, you
can animate its size or position, have it move in front of or behind other elements, or make it fade away
to nothing.

In the following example, you change the color of the document by modifying the background color CSS
attribute of the document object (it ’ s ok if you don ’ t understand this yet).

< html >
< body >
< script type=”text/javascript” >
document.body.style.backgroundColor = ‘green’;
< /script >
< /body >
< /html >

You can see this rendered in Internet Explorer in Figure 1 - 2.

Figure 1-2
The Browser Object Model (BOM)
JavaScript in a browser is essentially a group of object models relating to specific areas of functionality
within the browser. One of these is known as the BOM (Browser Object Model), which represents the
browser itself. The browser object can be accessed by referencing the top - level object window . From here
you can access things such as the document object, the frames collection, the browser history, the status
bar, and so on. In large part, what you find in the BOM depends on what browser you are operating in.
However, the main pieces can be seen in Figure 1 - 3.

The Document Object Model (DOM)
By far the most important object of all the available object models in a browser is the document . The
document gives access to all the elements on a page as a hierarchical collection of nodes. It also contains
some meta information about the page itself such as title and URL and gives access to some short - hand
collections of common elements like forms, links, and < a > tags (anchors). The document object can be
accessed from any part of a JavaScript application from window.document , or simply document .
The DOM is a very large object but some of the most common top - level properties can be found as
follows. A more complete reference with full browser support information is in Appendix F.





Document Property Description
body Returns a reference to the <body> container of the current page,
containing all the HTML on the page.
cookie Gives read and write access the cookies accessible by this page.
forms[ ] An array of all the forms on the page, including all the form fields
within them.
links[ ] An array of all the hyperlinks on the page.
location Gets and sets the location, or current URL, of the window object.
title The title of the document (defined in the <title> tag).
Window
document object frames collection history object location navigator object
Figure 1-3
You ’ ll look at this in more detail later, but for now it ’ s enough to know that the document is a
representation of the current page, is dynamic (can be modified via JavaScript calls), and is not exactly
the same between browser engines. For example, Internet Explorer document object contains methods

When to Use JavaScript
Sometimes it ’ s useful to consider the “ big picture ” when looking at a new technology. Once you
understand that, you can begin to anticipate the answers to other questions that might come up. One of
those “ big picture ” questions for JavaScript is what can it do and what can it not do . After all, it is a
scripting language and running inside a browser (usually) – – we know there must be limits to its power.
Let ’ s start with the types of things it can do :
Dynamically draw boxes, images, and text on the page: Using Dynamic HTML and the DOM,
you can arbitrarily style and animate these types of objects on a webpage.
Open and close windows: You can spawn new browser windows and communicate with them
to some degree. You can also create simulated windows using DHTML and even provide drag
and drop support for them like real windows that would appear elsewhere on the desktop.
Animate on - screen contents: You can create multiple, simultaneous, threaded animations using
DHTML, the DOM, and JavaScript timers.
Modify the document: You can create elements, text, and images, or you can delete or modify
existing ones.

Communicate with the server: Using Ajax and similar techniques, you can asynchronously
send messages back and forth between the server and the client without forcing the page to
re - load.
Talk to Java, Flash, Silverlight objects: You can even communicate with other types of media
embedded on the page to control the behavior of Flash and Silverlight movies or interface with
Java Applets.

Snoop on the user; record what they do: Yes, it ’ s even possible (however nefarious) to record
everything your website users are doing on a page, their mouse movements, keystrokes, and so
on, and study it later. There are benign uses for this data, too (for example web analytics).
Read the mouse/keyboard: You can keep detailed track of what the user is doing with the
keyboard and mouse in order to create extremely rich and interactive web applications.
Save data offline for later: You can put information in semi - permanent storage on the user ’ s
computer so that the next time they come to our page and want access to it, they can have it.
Create free - form graphic elements: Using complementary technologies like Canvas elements,
Scalable Vector Graphics, and Flash, you can put free - form elements on a page and even change
them on the fly.

Create accessible web pages: A common misconception is that it is not possible to have an
accessible web page for people with disabilities and still use JavaScript. Most web users with
disabilities are using browsers that do support JavaScript. Given a bit of care and attention, you
can make sure your pages are easy for them to use.

JavaScript in the Browser
Now I ’ m going to lay the foundation for the rest of this book. Since I ’ m going to be discussing
JavaScript generally as a language but also specifically as a tool for web development, you should
understand precisely how it interacts with the browser. This way, when I discuss ideas like the
Document Object Model (the DOM) or how JavaScript interacts with HTML in the examples later
in this book, you will know exactly what I am talking about.

JavaScript has been around long enough that all the major modern browsers (Internet Explorer,
Firefox / Netscape, Opera, Safari, and Chrome) pretty much work the same way when it comes to
handling scripts and how they interact with documents. Of course, there are a lot of differences
when you get down to the fine details, but in general terms browsers try to act in a consistent way
with one another. The general syntax of ECMAScript, the way you embed scripts on a page, and
the general structure of DOMs are more or less consistent. This is a good thing, because if it wasn ’ t
true, JavaScript development would be very difficult to learn.
The Document Object Model

I ’ ve already introduced the idea of the DOM (Document Object Model) in Chapter 1, but now we
need to look at its structure in more detail so that you understand how scripts interact with it.
The DOM serves as an object representation of all the elements and information pertaining to the
layout of the page. Technically speaking, a browser does not need a DOM to render a web page, but
it is required if it wants to allow JavaScript to read or write information to the page. Historically
this has been the most inconsistently implemented feature of web browsers, but in recent years this
problem has been mitigated thanks in large part to the work that the World Wide Web Consortium
(W3C) has done in documenting a standard for DOMs ( http://www.w3.org/DOM/ ).
An HTML document with only the most basic structure but no content might be written like this:

< html >
< head > < /head >
< body > < /body >
< /html >

Here I have a global < html > element that tells the browser to expect HTML content. Then I have a
< head > element, which should contain information about the document such as title, relevant search
keywords, and other relevant meta - data that is not, strictly speaking, layout or content. The < body > area
is where you put that. This would have an object representation in a DOM. In JavaScript, your DOM can
be accessed simply by referencing the global object document . To access the body element, you can
typically just reference document.body . If you wanted to access the HTML content of the < body >
element as a string, you could access the innerHTML property of that element ( document.body.
innerHTML ). This is the power of the DOM. If you think of your page as a hierarchical object model, it
becomes something you can represent easily in a JavaScript object.
If you were to draw an object hierarchy of this representation, it might look like Figure 2 - 1.

The SCRIPT Element
The < script > element is the way you embed JavaScript on a webpage. It ’ s an HTML element and can
be used to do one of two things:
Embed a script directly inline with the page content.
Reference (import) an external script document.
The following table contains all the generally supported attributes for this element:

Property Name Support Description
type 
CH1+, FF1+, IE5+, NN4+,
O5+, SF1+
Specifies the scripting language of the script.
The common values are text/ecmascript,
text/javascript, application/
ecmascript, application/javascript,
text/vbscript. Technically, the text/
javascript type is obsolete, but should still
be used due to lack of support for
application/javascript in earlier
versions of Explorer. When in XHTML, this
attribute is required.

charset
CH1+, FF1+, IE5+, NN4+,
O5+, SF1+
Specifies the character encoding to display
the script. The default for JavaScript files is
ISO-8859-1. This is only relevant for
external scripts (ones that use the src
attribute). The other common character set is
UTF-8.
defer IE5+ Specifies whether or not to delay execution of
the script until after the DOM has been
loaded. Eg: defer=“defer”.

language
CH1+, FF1+, IE5+, NN4+,
O5+, SF1+
Another way to specify the scripting
language of the script. Common values are:
JavaScript, JavaScript1.1,
JavaScript1.2, JavaScript1.3, JScript,
VBScript, and vbs. This feature has been
deprecated and type should be used instead.

src
CH1+, FF1+, IE4+, NN3+,
O5+, SF1+
Specifies the URL location of an external
script file. This is really useful for running the
same script on several pages, without having
to write the same script on every page. Both
absolute (http://myurl.com/script.js) and
relative (../js/script.js) URLs are allowed.

The following is an example of a typical inline script embed:
< html >
< head > < /head >
< body >
< h1 > Hello World < /h1 >
< script type=”text/javascript” > >
alert(‘hello!’);
< /script >
< /body >
< /html >
If your script was external to the document, you might include it in this way:
< html >
< head >
< script src=”/js/script.js” type=”text/javascript” > < /script >
< /head >
< body > < /body >
< /html >

You can place script elements in either the < head > or < body > areas of a document. Generally, if external
scripts are imported using the src attribute, they are placed in the < head > . If you ’ re concerned that
downloading an external script will unnecessarily delay the loading of a page, you can place it directly
before the closing body tag < /body > .

There are advantages to referencing scripts externally using the SRC attribute versus embedding them
on the page. One is that you can take advantage of caching. Generally speaking, once the browser has
downloaded an external script, it will keep it in memory the next time a page is loaded that references it.
This means it doesn ’ t have to re - download the contents of the script every time the page loads. For
particularly large scripts, this can mean a real improvement in page - load performance.

Over the years that browsers have supported scripting in one form or another, there have been quite a
few different versions of the language put forth. Microsoft even supports another scripting language,
VBScript, in lieu of JavaScript if the developer desires. I ’ ve already shown here that the language
attribute can force the browser to interpret the script as a particular language. All modern browsers will
assume a default language of “ JavaScript ” assuming compatibility with ES3.

Inline Scripts
When I refer to inline scripts, I mean scripts meant to be executed as soon as they are encountered if the
page were read from top to bottom. These can appear in both the < head > and < body > areas of the page.
Here ’ s an example:

< html >
< head >
< script type=”text/javascript” > >
alert(‘Test1’);
< /script >
< /head >
< body >
< h1 > Hello World < /h1 >
< script type=”text/javascript” >
alert(‘Test2’);
< /script >
< h2 > I am another dom element. < /h2 >
< /body >
< /html >

If you bring this page up in your browser, the first thing you ’ ll see is Figure 2 - 3.

Followers