0% found this document useful (0 votes)
10 views57 pages

Javascript

The document introduces JavaScript as a key language for creating dynamic web pages, detailing its relationship with HTML and CSS. It emphasizes the importance of separating code for structure, design, and behavior, and suggests using editors like Sublime Text or Atom for development. Additionally, it outlines the process of embedding JavaScript in HTML and provides a simple example to illustrate the concept.

Uploaded by

dedesbk
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views57 pages

Javascript

The document introduces JavaScript as a key language for creating dynamic web pages, detailing its relationship with HTML and CSS. It emphasizes the importance of separating code for structure, design, and behavior, and suggests using editors like Sublime Text or Atom for development. Additionally, it outlines the process of embedding JavaScript in HTML and provides a simple example to illustrate the concept.

Uploaded by

dedesbk
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Build and deepen your coding knowledge

from the top programming experts!

Reading Sample
In these sample chapters you’ll first learn about the ways in which
you can embed JavaScript in a web page and generate simple out-
put, and then see how you can use the jQuery library to simplify
different JavaScript programming tasks.

“Getting Started”

“Simplifying Tasks with jQuery”

Contents

Index

The Author

Philip Ackermann
JavaScript: The Comprehensive Guide
982 pages, 2022, $59.95
ISBN 978-1-4932-2286-5

[Link]/5554
Chapter 2
2
Getting Started
JavaScript is still mainly used for creating dynamic web pages—within a
browser. Before we take a closer look at other application areas in later
chapters, this chapter will show you the ways in which you can embed
JavaScript in a web page and generate simple output. This chapter thus
is the basis for the following chapters.

Before we go into further detail about the JavaScript language itself, you should first
know how JavaScript relates to HTML and CSS within a web page, how to embed Java-
Script in a web page, and how to generate output.

2.1 Introduction to JavaScript and Web Development


The most important three languages for creating web frontends are certainly HTML,
CSS, and JavaScript. Each of these languages serves its own purpose.

2.1.1 The Relationship among HTML, CSS, and JavaScript


In HTML, you use HTML elements to specify the structure of a web page and the mean-
ing (semantics) of individual components on a web page. For example, they describe
which area on the web page is the main content and which area is used for navigation,
and they define components such as forms, lists, buttons, input fields, or tables, as
shown in Figure 2.1.

Figure 2.1 HTML Is Used to Define the Structure of a Web Page

55
2 Getting Started 2.1 Introduction to JavaScript and Web Development

CSS, on the other hand, uses special CSS rules to determine how the individual compo-
nents that you have previously defined in HTML should be displayed; this is used to
2
define the design and layout of a web page. For example, you can define text color, text
size, borders, background colors, color gradients, and so on. Figure 2.2 shows how CSS
was used to adjust the font and font size of the table headings and table cells, add bor-
ders between table columns and table rows, and alternate the background color of the
table rows. The whole thing looks a lot more appealing than the variant without CSS.

Figure 2.4 Filter Option to Make a Web Page More User-Friendly and Interactive
with JavaScript

Thus, in the vast majority of cases, a web page consists of a combination of HTML, CSS,
and JavaScript code (see Figure 2.5). Note that though we just said that JavaScript takes
care of the behavior of a web page, you can create functional web pages entirely with-
out JavaScript. In principle, you can also create web pages without CSS; it is possible. In
that case, only the HTML is evaluated by the browser. That means, however, that the
web page is less fancy (without CSS) and less interactive and user-friendly (without
JavaScript), as shown previously in Figure 2.1.
Figure 2.2 With CSS, You Define the Layout and Appearance of Individual Elements of the
Web Page
HTML (Structure)

Last but not least, JavaScript is used to add dynamic behavior to the web page (or to the
components on a web page) or to provide more interactivity on the web page. Exam-
ples of this are sorting and filtering the table data, as already mentioned in Chapter 1
(see Figure 2.3 and Figure 2.4). So while CSS takes care of the design of a web page, Java-
CSS (Layout) Web Page
Script can be used to improve the user experience and interactivity of a web page.

JavaScript
(Interaction)

Figure 2.5 Usually, a Combination of HTML, CSS, and JavaScript


Is Used within a Web Page

Note
HTML is used for the structure of a web page, CSS for layout and design, and JavaScript
for behavior and interactivity.
Figure 2.3 Sort Option to Make a Web Page More User-Friendly and Interactive with
JavaScript

56 57
2 Getting Started 2.1 Introduction to JavaScript and Web Development

the design with CSS, while a web developer programs the functionality in JavaScript (in
Definition practice, the web designer and web developer are often one and the same person, but
2
Web and software developers also refer to three layers in this context: HTML provides especially in large projects with numerous websites, a distribution of responsibilities is
the content layer, CSS the presentation layer, and JavaScript the behavioral layer. not uncommon).

Phases of Website Development


Separating the Code for the Individual Layers When developing professional websites, there are several stages preceding the devel-
It is considered good development style not to mix the individual layers—that is, to opment step. Before development even begins, prototypes are designed in concept and
keep HTML, CSS, and JavaScript code independent of each other and in separate files. design phases (either digitally or quite classically with pen and paper). The step-by-step
This makes it easier to keep track of a web project and ultimately ensures that you can approach just described (first HTML, then CSS, then JavaScript) thus only refers to
develop more effectively. In addition, this method enables you to include the same CSS development.
and JavaScript files in various HTML files (see Figure 2.6) and thus to reuse the same
CSS rules or JavaScript source code in several HTML files.
HTML Markup Language and CSS Style Language
JS HTML By the way, HTML and CSS are not programming languages! HTML is a markup lan-
guage and CSS is a style language; only JavaScript of the languages we’re discussing
here is a programming language. Strictly speaking, statements like "This can be pro-
grammed with HTML" are therefore not correct. You'd instead have to say something
HTML
like "This can be realized with HTML."

CSS

JS HTML Definition
The process of presenting a web page in the browser is called rendering. A common
phrase among developers is "The browser renders a web page." This involves evaluat-
HTML ing HTML, CSS, and JavaScript code, creating an appropriate model of the web page
(which we'll talk about in Chapter 5), and "drawing" the web page into the browser
window. In detail, this process is quite complex, and if you’re interested in this topic,
Figure 2.6 If You Write CSS and JavaScript Code into Separate Files rather than Directly you might want to read the blog post at [Link]/en/tutorials/internals/
into the HTML Code, It Is Easier to Reuse howbrowserswork.

A good approach to developing a website is to think about its structure first: What are
the different areas of the web page? What are the headings? Is there any data presented 2.1.2 The Right Tool for Development
in tabular form? What are the navigation options? Which information is included in In principle, a simple text editor would be sufficient for creating JavaScript files (and for
the footer area and which in the header area of the page? Only HTML is used for this simple code examples this is perfectly fine), but sooner or later you should acquire a
purpose. The website won’t look nice or be very interactive, but that isn’t the point of good editor that supports you when writing JavaScript and that is specifically designed
this first step, in which we do not want to be distracted from the essential element: the for developing JavaScript programs (if you don't already have one installed on your
website content. computer anyway). Such an editor supports you, for example, by highlighting the
Building on this structural foundation, you then implement the design using CSS and source text in color, relieving you of writing recurring source text modules, recogniz-
the behavior of the web page using JavaScript. In principle, these two steps can also be ing errors in the source text, and much more.
carried out in parallel by different people. For example, a web designer may take care of

58 59
2 Getting Started 2.1 Introduction to JavaScript and Web Development

Editors
There are a number of really good editors that can be used effectively. For example, 2
Sublime Text ([Link]; see Figure 2.7) and Atom ([Link] see
Figure 2.8), both available for Windows, macOS, and Linux, are popular editors in the
developer community. While the former currently costs $99 (as of June 2021), the Atom
editor is free of charge. In detail, both editors have their own features and strengths,
but they are still quite similar. Try them out to see which one suits you more.

Figure 2.8 Atom Editor

Development Environments
Software developers switching from languages like Java or C++ to JavaScript are in most
cases used to integrated development environments (IDEs), as known from their previ-
ous programming languages. In a way, you can think of a development environment as
a very powerful editor that provides various additional features compared to a "nor-
mal" editor, such as synchronization with a source control system, running automatic
Figure 2.7 Sublime Text Editor builds, or integrating test frameworks. (If you're just shaking your head uncompre-
hendingly now and wondering what's behind all these terms, wait until Chapter 21, in
which we’ll go into more detail about these advanced topics of software development
with JavaScript.)

60 61
2 Getting Started 2.1 Introduction to JavaScript and Web Development

WebStorm by IntelliJ ([Link]/webstorm/; see Figure 2.9) is one example of


a very popular and also very good development environment. A single license for Web-
2
Storm currently costs USD 129 (for personal use, there is another version that currently
costs USD 59). However, if you want to test the program first, you can download a 30-
day trial version from the WebStorm homepage. WebStorm is available for Windows
and for macOS and Linux.

Figure 2.10 Microsoft Visual Studio Code

Name Price macOS Linux Windows Editor/Development


Environment

Sublime Text USD 99 Yes Yes Yes Editor

Atom Free of charge Yes Yes Yes Editor

Microsoft Free of charge Yes Yes Yes Development


Visual Studio environment
Code
Figure 2.9 WebStorm IDE
WebStorm USD 129/ Yes Yes Yes Development
USD 59 environment
Meanwhile a personal favorite among the development environments is Visual Studio
Code by Microsoft ([Link] see Figure 2.10). It is available for Table 2.1 Recommended Editors and Development Environments for JavaScript
download free of charge, can be flexibly extended via plug-ins, and its perceived perfor- Development
mance is significantly better than that of WebStorm, for example.
A brief overview of the editors and development environments we’ve discussed is
Tip
shown in Table 2.1.
For the beginning—for example, for trying out the code examples in this book—we
recommend that you use one of the editors mentioned in this section and not a

62 63
2 Getting Started 2.2 Integrating JavaScript into a Web Page

However, it is a good idea to create different folders for the CSS and JavaScript files. The
development environment (yet). The latter have the disadvantage that they are
names styles (for CSS files) and scripts (for JavaScript files) are quite common. Especially
partly overloaded with menus and functionalities, so you have to deal not only with 2
if you are dealing with a lot of different JavaScript and CSS files during development,
learning JavaScript but also with learning the development environment. Let’s spare
this separation (or an arrangement with subfolders in general) makes it easier to keep
you that at least for the moment.
track of your project.
In addition, development environments only make sense when exceeding a certain
project size. For smaller projects and the examples in this book, an editor is always
enough (even though we will also cover complex topics). Plus, the editors are usually Starting Point of a JavaScript Application
faster than the development environments in terms of execution speed. Most of the examples in this book also follow the layout shown in Figure 2.11 as we will
only run the JavaScript code in the browser at the beginning, using the [Link] file
as a kind of entry point to the program.
Later, in Chapter 17, you’ll learn how you can also run JavaScript independent of a
2.2 Integrating JavaScript into a Web Page
browser and thus independent of a corresponding HTML file. In this case, you don’t
Because we assume that you already know how to create an HTML file and how to need any HTML—and therefore no CSS files either.
embed a CSS file, and that you are "only" here to learn JavaScript, we don't want to waste
any more time with details about HTML and CSS but will get started with JavaScript
straight away. Don’t worry: embedding and executing a JavaScript file is anything but Running JavaScript in the Browser
difficult. While you can execute JavaScript within a browser without creating an HTML file to
embed the corresponding script (via special developer tools provided by browsers; Sec-
Learn HTML and CSS tion 2.3.2), for now we don’t want to use this feature.

If you have not worked with HTML or CSS a very good introductory book on this topic is
HTML and CSS: Design and Build Websites by Jon Duckett (2011, John Wiley & Sons).
2.2.2 Creating a JavaScript File

Per tradition (like almost every book on programming languages), we will start with a As mentioned earlier, it’s better to save JavaScript code in a separate file (or in several
very simple Hello World example, which only produces the output Hello World. This is separate files) that can then be embedded in the HTML code. So the first thing you need
not very exciting yet, but right now the point is to show you how to embed a JavaScript is a JavaScript file. Simply open the editor of your choice (or if you didn't take my
file in an HTML file in the first place and how to execute the source code contained in advice, the development environment of your choice), create a new file, enter the lines
the JavaScript file. We will take care of more complex things later. of source code provided in Listing 2.1, and then save the file under the name [Link].

function showMessage() {
alert('Hello World');
2.2.1 Preparing a Suitable Folder Structure
}
For getting started and working through the following examples, we recommend that
Listing 2.1 A Very Simple JavaScript Example That Defines a Function
you use the directory structure shown in Figure 2.11 for every example. The HTML file is
at the top level because this is the entry point for the browser and thus the file you will
invoke in the browser right away.
Note
JavaScript files have the extension .js. Other file extensions are also possible, but the .js
extension has the advantage that editors, development environments, and browsers
directly know what the content is about. You should therefore always save all Java-
Script files with the .js extension. (By the way, browsers recognize JavaScript files deliv-
ered by a web server via the Content-Type header, a piece of information that comes
with the file from the server.)
Figure 2.11 Example Folder Structure

64 65
2 Getting Started 2.2 Integrating JavaScript into a Web Page

Listing 2.1 defines a function with the name showMessage, which in turn calls another
Attribute Meaning Comment
function (with the name alert) and passes it the message Hello World. The alert func-
2
tion is a JavaScript standard function, which we will briefly discuss later in this chapter. charset Specifies the character set of the source code that is embedded Optional
via the src attribute. This only makes sense in combination with
Functions in general, however, will be detailed in Chapter 3.
the src attribute, but is rarely used because most browsers do
not respect this attribute. It is also considered better style to use
Supplemental Downloads for the Book UTF-8 everywhere within a website and define this in the
This code example and all those to come can also be found in the Product Supplements <meta> element via the charset attribute.
area for the book (see [Link] There you can defer Specifies whether to wait to execute the linked JavaScript file Optional
easily download the code and open it in your editor or directly in your browser until the web page content has been completely processed (Sec-
(although we think that the most effective way to learn is to type the examples your- tion 2.2.5). This only makes sense in combination with the src
self, following them step by step). attribute, but is not always supported, especially not by older
browsers.

language Originally intended to indicate the version of JavaScript code Outdated


2.2.3 Embedding a JavaScript File in an HTML File used, but largely ignored by browsers.
To use the JavaScript source code within a web page, you need to link the JavaScript file src Specifies the path to the JavaScript file to be embedded. Optional
to the web page or embed the JavaScript file in the HTML file. This is done via the HTML
element named <script>. type Used to specify the MIME type (see box ahead) in order to iden- Optional
tify the scripting language (in our case, JavaScript). However, you
This element can be used in two different ways: On the one hand, as we will demon- can also omit this attribute because text/javascript is used
strate subsequently, external JavaScript files can be included in the HTML. On the other by default, which is supported by most browsers.
hand, JavaScript source code can be written directly between the opening <script> tag
Table 2.2 The Attributes of the <script> Element (Cont.)
and the closing </script> tag.
An example of the latter method will be shown later, but this approach is only useful in
Now create an HTML file named [Link] and insert the content shown in Listing 2.2.
exceptional cases because JavaScript code and HTML code are then mixed—that is,
stored in one file (which is not a best practice for the reasons already mentioned). So <!DOCTYPE html>
let's first look at how to do it properly and include a separate file. <html>
<head lang="en">
The <script> element has a total of six attributes, out of which the src attribute is cer-
<meta charset="UTF-8">
tainly the most important one: it’s used to specify the path to the JavaScript file that is
<title>Example</title>
to be included. (Table 2.2 shows an overview of what the other attributes do.) <link rel="stylesheet" href="styles/[Link]" type="text/css">
</head>
Attribute Meaning Comment
<body>
async Specifies whether the linked JavaScript file should be down- Optional <!--Here the JavaScript file will be included -->
loaded in an asynchronous way in order not to interrupt the <script src="scripts/[Link]"></script>
download of other files (Section 2.2.5). This only makes sense in </body>
combination with the src attribute. </html>

Table 2.2 The Attributes of the <script> Element Listing 2.2 Embedding JavaScript in HTML

If you now open this HTML file in the browser, nothing will happen yet because the
function we defined in Listing 2.1 is not yet called at any point. Therefore, add the show-
Message() call at the end of the JavaScript file, as shown in Listing 2.3, and reload the web
page in the appropriate browser. Then a small hint dialog should open, containing the

66 67
2 Getting Started 2.2 Integrating JavaScript into a Web Page

message Hello World and with a slightly different appearance depending on the
browser (see Figure 2.12). Embedding Multiple JavaScript Files
2
Of course, you can embed several JavaScript files within one HTML file. Simply use a
function showMessage() {
separate <script> element for each file you want to include.
alert('Hello World');
}
showMessage();
2.2.4 Defining JavaScript Directly within the HTML
Listing 2.3 Function Definition and Function Call
For the sake of completeness, we’ll also show how you can define JavaScript directly
within an HTML file. While this is usually not advisable because it means mixing HTML
and JavaScript code in one file, it won’t hurt to know that it still works.
Simply write the relevant JavaScript code inside the <script> element instead of linking
it via the src attribute. Listing 2.4 shows the same example as in the previous section,
but it doesn’t use a separate JavaScript file for the JavaScript code. Instead, it embeds
the code directly in the HTML. The src attribute is therefore omitted completely.
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Example</title>
<link rel="stylesheet" href="styles/[Link]" type="text/css">
</head>
<body>
Figure 2.12 Hint Dialogs in Different Browsers <script>
function showMessage() {
alert('Hello World');
Definition }
Multipurpose Internet Mail Extension (MIME) types, also called internet media types or showMessage();
content types, were originally intended to distinguish between content types within </script>
emails containing different content (such as images, PDF files, etc.). Now, however, </body>
MIME types are not only used in the context of email, but also whenever data is trans- </html>
mitted over the internet. If a server sends a file with a special MIME type, the client
Listing 2.4 Only Makes Sense in Exceptional Cases: Definition of JavaScript
(e.g., the browser) knows directly what type of data is being transmitted.
Directly in an HTML File
For JavaScript, the MIME type wasn’t standardized for a long time, so there were sev-
eral MIME types—for example, application/javascript, application/ecmascript,
text/javascript and text/ecmascript. Since 2006, however, there is an official stan- Note
dard ([Link]/rfc/[Link]) that defines the acceptable MIME types for
Note that <script> elements that use the src attribute must not contain any source
JavaScript. According to this standard, text/javascript and text/ecmascript are both
code between <script> and </script>. If there is any, this source code will be ignored.
deprecated, and application/javascript and application/ecmascript should be
used instead. Ironically, it’s safest not to specify any MIME type for JavaScript at all (in
the <script> element) as the type attribute is ignored by most browsers anyway.

68 69
2 Getting Started 2.2 Integrating JavaScript into a Web Page

Process HTML Process HTML


Tip
2
Use separate JavaScript files for your source code instead of writing it directly into a
<script> element. This creates a clean separation between the structure (HTML) and Download JavaScript File
the behavior (JavaScript) of a web page. Execute JavaScript
Source Code

Figure 2.13 By Default, HTML Code Processing Stops when the Browser Encounters
The <noscript> Element a <script> Element
You can use the <noscript> element to define an HTML section that is displayed when
JavaScript is not supported in the browser or has been disabled by the user (see Listing In addition, you will often want to access HTML elements on a web page within the
2.5). However, if JavaScript is supported or enabled, the content of the <noscript> ele- JavaScript source code. (You’ll see how this works in Chapter 5.) If the JavaScript code is
ment will not be shown. executed before these HTML elements have been processed, you’ll encounter an access
<noscript> error (see Figure 2.14). If you place the <script> element before the closing </body> tag,
JavaScript is not available or is disabled. <br /> though, you are on the safe side in this regard (see Figure 2.15), because in that case all
Please use a browser that supports JavaScript, elements included inside the <body> element are already loaded (with the exception of
or enable JavaScript in your browser. other <script> elements, of course).
</noscript>
Process HTML Process HTML
Listing 2.5 Example of the Use of the <noscript> Element Download JavaScript
File
HTML Elements
Not Loaded before
This Point Cannot
2.2.5 Placement and Execution of the <script> Elements Be Accessed
Execute JavaScript
Source Code
If you had asked a web developer a few (many) years ago where to place a <script> ele-
ment within a web page, they probably would have advised placing it in the <head> area Figure 2.14 If JavaScript Accesses HTML Elements That Have Not Yet Been Loaded,
of the web page. In the early days of web development, people thought that linked files an Error Occurs
such as CSS files and JavaScript files should be placed in a central location within the
HTML code.
HTML Elements Can Be Accessed
Since then, however, this idea has been abandoned. While CSS files are still placed in the Process HTML
Download JavaScript
<head> area, JavaScript files should be included before the closing </body> tag instead.
File
The reason is this: when the browser loads a web page, it loads not only the HTML code
but also embedded files such as images, CSS files, and JavaScript files. Depending on
processor performance and memory usage, modern browsers are capable of download- Execute JavaScript
Source Code
ing several such files in parallel. However, when the browser encounters a <script> ele-
ment, it immediately starts processing the corresponding source code and evaluating Figure 2.15 If the <script> Element Is Placed before the Closing </body> Tag,
it using the JavaScript interpreter. To be able to do this, the corresponding JavaScript All Elements inside the <body> Element Are Loaded
source code must first be downloaded entirely. While this is happening, the browser
pauses downloading all other files and parsing (i.e., processing) the HTML code, which
in turn leads to the user impression that it takes longer to build the web page (see Note
Figure 2.13). As a rule, you should position <script> elements at the end of the <body> element. This
is because the browser first evaluates the JavaScript source code contained or embed-
ded in each <script> element before continuing to load other HTML elements.

70 71
2 Getting Started 2.2 Integrating JavaScript into a Web Page

Two attributes that can be used to influence the loading behavior of JavaScript are the
async and defer attributes, which we already mentioned briefly (see Table 2.2). The for- Definition
2
mer ensures that the processing of HTML code is not paused when the browser encoun- Another way to ensure that all the content of the web page has been loaded before
ters a <script> element. The JavaScript file is downloaded asynchronously (hence the JavaScript code is executed is to use event handlers and event listeners. We’ll introduce
name async). This concept is shown in Figure 2.16. both of them in detail in Chapter 6. But for now, we’ll show you roughly how both of
them are used because they appear in the source code examples in the book before we
Process HTML Process HTML get to the examples for Chapter 6.
In general, both event handlers and event listeners are used to respond to certain
events that occur during the execution of a program and to execute certain code.
Download JavaScript File
(There is a small, subtle difference between event handlers and event listeners, but it's
Execute JavaScript
Source Code not important for now, and we'll explain it in Chapter 6.) Events can be mouse clicks,
keystrokes, window resizing actions, and more. For web pages, too, there are various
Figure 2.16 Due to the async Attribute, the HTML Code Continues To Be Processed until the events that are triggered and can be answered by such event handlers and event listen-
Corresponding JavaScript Has Been Downloaded ers. For example, an event is triggered when the content of a web page is fully loaded.
To define an event handler for this event, you can use the onload attribute: The code
As you can see, the JavaScript code is executed right away as soon as the corresponding
you specify here as the value for such an attribute is invoked when the web page is
JavaScript file has been completely downloaded.
fully loaded. As a value, you can specify a JavaScript statement, such as the call to a
The defer attribute takes this one step further. On the one hand, just like async, this function, as shown in Listing 2.6.
attribute ensures that the HTML code processing is not paused. On the other hand, the <!DOCTYPE html>
JavaScript source code is executed only after the HTML code has been fully processed <html>
(see Figure 2.17). The execution of the JavaScript code is effectively deferred (hence the <head lang="en">
name defer). <meta charset="UTF-8">
<title>Example</title>
Process HTML <link rel="stylesheet" href="styles/[Link]" type="text/css">
</head>
<body onload="showMessage()">
Download JavaScript File <script src="scripts/[Link]"></script>
Execute JavaScript </body>
Source Code </html>

Figure 2.17 The defer Attribute Ensures That the Corresponding JavaScript Is Only Executed Listing 2.6 Using an Event Handler
after the Entire HTML Code of the Web Page Has Been Loaded
Event listeners, however, cannot be defined via HTML. Instead, you use the addEvent-
Listener() function of the document object (more on this later), to which you pass the
So when should you use which attribute? For now, you can bear in mind that it’s prob-
name of the event and the function to be executed when the event is triggered (see Lis-
ably best not to use either attribute by default. The async attribute is only suitable for
ting 2.7).
scripts that work completely independently and have nothing to do with the HTML on
function showMessage() {
the web page. An example of this is the use of Google Analytics. The defer attribute, on
alert('Hello World');
the other hand, is currently not supported by all browsers, so you should also consider
}
its use with caution.
[Link]('DOMContentLoaded', showMessage);
Listing 2.7 Using Event Listeners

72 73
2 Getting Started 2.2 Integrating JavaScript into a Web Page

The showMessage() call you just added to the end of the [Link] file will need to be
removed again in both cases. Otherwise, the function will be called twice (once by the 2
script itself and once by the event handler/event listener), and as a consequence a
message dialog will be displayed twice in succession.

2.2.6 Displaying the Source Code


All browsers usually provide a way to view the source code of a web page. This can be
helpful in many cases—for example, if you want to check how a particular feature is
implemented on a website you have discovered.
Figure 2.19 Show Source Code in Firefox
In Chrome, you can view the source code by following menu path View • Developer •
View Source (see Figure 2.18); in Firefox, Tools • Browser Tools • Page Source (see Figure
2.19); in Safari, Develop • Show Page Source (see Figure 2.20); in Opera, Developer • View
Source (see Figure 2.21); and in Microsoft Edge, Tools • Developer • View Source (see
Figure 2.22).

Figure 2.20 Show Source Code in Safari

Figure 2.18 Show Source Code in Chrome Figure 2.21 Show Source Code in Opera

Source Code for More Complex Web Pages


If you look at the source code of more complex web pages, it’s often very confusing.
This is usually due to multiple reasons: on the one hand, content is often generated
dynamically, and on the other, JavaScript is often deliberately compressed and
obscured by web developers—the former to save space, the latter to protect the source
code from prying eyes. This book does not deal with the compression and obfuscation
of source code. Figure 2.22 Show Source Code in Microsoft Edge

74 75
2 Getting Started 2.3 Creating Output

If you display the source code of a web page (no matter in which browser), you are first
presented with the corresponding HTML code of the web page. Conveniently, however,
2
embedded files such as CSS files or JavaScript files are linked in this source code view
(see Figure 2.23) so that you can easily get to the source code of the linked file as well
(see Figure 2.24).

Figure 2.25 Simple Hint Dialog

Figure 2.26 Simple Confirmation Dialog

Figure 2.23 Source Code View for HTML in Chrome

Figure 2.27 Simple Input Dialog

In practice, however, these standard dialogs for hints, confirmation, and input are
Figure 2.24 Source Code View for JavaScript in Chrome rarely used because they offer limited options for statements and—as already shown
for the hint dialog—their design relies on the layout of the browser being used, which
usually does not match the layout of the web page.
2.3 Creating Output For this reason, web developers like to resort to one of the various JavaScript libraries
that offer fancier and more functional dialogs (see Figure 2.28). One of these libraries is
In the Hello World example, you have already seen how you can create simple output
jQuery UI, which builds on the well-known jQuery library and extends it with various
by calling the alert() function. However, there are several other options as well.
UI components. We will take a closer look at the main library, jQuery, as well as jQuery
UI in Chapter 10.
2.3.1 Showing the Standard Dialog Window
In addition to the already known hint dialog displayed by calling the alert() function
(see Figure 2.25), the JavaScript language provides two more standard functions for dis-
playing dialog boxes. The first one is the confirm() function. It’s used to display confir-
mation dialogs—that is, yes/no decisions (see Figure 2.26). In contrast to the hint
dialog, the confirmation dialog contains two buttons: one to confirm and one to cancel
the corresponding message. The second one is the prompt() function. This function Figure 2.28 Custom Confirmation Dialog with JavaScript
opens an input dialog where users can enter text (see Figure 2.27).

76 77
2 Getting Started 2.3 Creating Output

2.3.2 Writing to the Console Figure 2.29 shows the console in the Chrome browser, for example. As you can see, it
doesn’t really look special, but it will be one of your main tools if you want to use Java-
When developing JavaScript applications, you’ll often want to generate output for 2
Script for web development. In addition to receiving output, you can also enter your
yourself for testing purposes only—for example, to return an intermediate result. For
input via the console (more about this in a few moments). In essence, the console is a
such test-only output, it obviously doesn't make sense to present it in dialogs that
kind of terminal (or command prompt, if you're a Windows user) that lets you issue
users would get to see as well. For this reason, all current browsers now offer a console,
JavaScript commands that are then executed in the context of the web page loaded.
which is suitable for exactly such purposes and which you can access within a Java-
Script program in order to output messages. By default, this console is hidden because
users of a web page usually can do little with it. Writing Output to the Console
For writing to the console, browsers provide the console object. This is a JavaScript
Displaying the Console object first introduced by the Firefox plug-in named Firebug ([Link]
and it provides various ways to generate output to the console. Firebug itself has been
To activate the console, proceed as follows, depending on your browser (we won’t pro-
discontinued, but the console object (although still not included in the ECMAScript
vide screenshots at this point as the menu items can be found in similar places as the
standard) is available in almost every JavaScript runtime environment.
menu items for displaying the source code, mentioned earlier in this chapter):
쐍 In Chrome, select View • Developer • JavaScript Console, which opens the console
within the Chrome DevTools.
Standardized API for Working with the Console
The individual methods provided by the console object differ from runtime environ-
쐍 In Firefox, open the console via Tools • Browser Tools • Browser Console.
ment to runtime environment. To counteract this, there are efforts underway to create
쐍 In Safari, open the console via Develop • Show JavaScript Console.
a standardized API.
쐍 In Opera, you must first select Developer • Developer Tools and then the Console tab.
쐍 In Microsoft Edge, open the console via Tools • Developer • JavaScript Console. A generally supported method is the log() method, which can be used to generate sim-
ple console output. To try using the console, simply replace the source code of the
[Link] file with the source code in Listing 2.8 and call the web page again.

// scripts/[Link]
function showMessage() {
[Link]('Hello developer world');
}

Listing 2.8 Simple JavaScript Example

Depending on the browser, the result should be similar to that shown in Figure 2.30.

Figure 2.30 Output to the Console in Chrome


Figure 2.29 By Default, the Console Is Displayed on the Right or at the Bottom of the Browser
Window (Google Chrome in This Case)

78 79
2 Getting Started 2.3 Creating Output

In addition to the log() method, console provides several other methods. An overview Writing Input to the Console
of the most important ones is provided in Table 2.3. In the last few screenshots, you may have noticed the > sign below the output. Here, 2
you can enter any JavaScript code and have it executed right away. This is a great way
Method Description
to quickly test simple scripts, and actually indispensable for web development. Try it:
clear() Clears the console. type the showMessage() command in the prompt and then press the (Enter) key to exe-
cute the command. The results are displayed in Figure 2.32.
debug() Used to output a message intended for debugging (or troubleshooting). (You
may first need to set the appropriate developer tools to return this type of out-
put.)

error() Used to output an error message. Some browsers display an error icon next to
the output message within the console.

info() This will display an info message in the console. Some browsers—Chrome, for
example—also output an info icon.
Figure 2.32 You Can Also Execute Source Code via the Console
log() Probably the most commonly used method of console. Generates normal out-
put to the console.

trace() Outputs the stack trace—that is, the method call stack (see also Chapter 3) to Note
the console. The console window and the console object are important tools for web developers.
Make yourself familiar with both when you get a chance.
warn() Used to issue a warning to the console. Again, most browsers will display a cor-
responding icon next to the message.

Table 2.3 Most Important Methods of the console Object Logging Libraries
The console object works well for quick output during development. However, if a web
Listing 2.9 shows the corresponding source code for using the console object. The out- page goes live or a JavaScript application is used in production, you don't really want to
put for the individual methods is highlighted with colors or icons, depending on the use console calls any longer (even though they are usually not displayed to the user). In
browser (see Figure 2.31). practice, you often use special logging libraries that enable console output to be acti-
vated (for development) but also deactivated again (for productive use) via specific
[Link]('Hello developer world'); // Output of a normal message
[Link]('Hello developer world'); // Output of a debug message
configuration settings. To start, and also for the examples in this book, however, the
[Link]('Hello developer world'); // Output of an error message use of the console object should be sufficient.
[Link]('Hello developer world'); // Output of an info message
[Link]('Hello developer world'); // Output of a warning
2.3.3 Using Existing UI Components
Listing 2.9 Using the console Object
Because the use of alert(), confirm(), and prompt() is rather outdated and only useful
for quick testing, and the output via the console object is reserved for developers any-
way, you obviously still need a way to create an appealing output for the user of a web
page. To this end, you can write the output of a program into existing UI components
such as text fields and the like.
Listing 2.10, Listing 2.11, and Figure 2.33 show an example. It consists of a simple form
that can be used to determine the result of adding two numbers. The two numbers can
be entered into two text fields, the addition is triggered by pressing the button, and the
Figure 2.31 Different Message Types Are Highlighted with Colors or Icons result is written into the third text field.

80 81
2 Getting Started 2.4 Summary

You don't need to understand the code for this example yet, and we won’t into the
details at this point. For now, just keep in mind that when developing for the web with
2
JavaScript, it's relatively common to use HTML components for sending output from a
program to the user.

// scripts/[Link] Figure 2.33 Example Application


function calculateSum() {
const x = parseInt([Link]('field1').value);
const y = parseInt([Link]('field2').value); DOM Manipulation
const result = [Link]('result');
The most complex scenario is when you dynamically modify a web page to produce
[Link](x + y);
output—for example, dynamically modify a table to display tabular structured data.
[Link] = x + y;
We will discuss this topic of DOM manipulation in more detail in Chapter 5.
}

Listing 2.10 The JavaScript Code of the [Link] File

<!DOCTYPE html> 2.4 Summary


<html>
In this chapter, you learned how to create JavaScript files and embed them in HTML.
<head lang="en">
You now have the basic knowledge for executing the examples in the next chapters.
<meta charset="UTF-8">
The following key points were presented in this chapter:
<title>Example</title>
<link rel="stylesheet" href="styles/[Link]" type="text/css"> 쐍 Three languages are important for frontend development: HTML as a markup lan-
</head> guage to define the structure of a web page, CSS as a style language to define design
<body> and layout, and JavaScript as a programming language to add additional behavior
<div class="container"> and interactivity to a web page.
<div class="row"> 쐍 You can specify JavaScript directly using the <script> element or can embed a sepa-
<label for="field1">X</label> <input id="field1" type="text" value="5"> rate JavaScript file using the src attribute of the <script> element. We recommend
</div>
the latter, as it ensures a clean separation between the structure (HTML) and behav-
<div class="row">
ior (JavaScript) of the web page.
<label for="field2">Y</label> <input id="field2" type="text" value="5">
</div> 쐍 You should always place <script> elements before the closing </body> tag, as this
<div class="row"> ensures that the web page content is fully loaded.
<label for="result">Result: </label> <input id="result" type="text"> 쐍 JavaScript inherently provides three functions for generating output: alert() for
<button onclick="calculateSum()">Calculate sum</button> creating hint dialogs, confirm() for creating confirmation dialogs, and prompt() for
</div> creating input dialogs.
</div>
쐍 In practice, however, instead of these (more or less obsolete) functions, people use
<script src="scripts/[Link]"></script>
fancier dialogs, such as those offered by the jQuery library.
</body>
</html> 쐍 In addition, all current browsers provide the possibility to generate output via a con-
sole, which is primarily intended for you to use as a developer.
Listing 2.11 The HTML Code for the Example Application

82 83
Chapter 10
Simplifying Tasks with jQuery
Many tasks that can now be performed relatively easily with JavaScript
were for a long time only possible with a relatively large amount of
source code due to browser differences. For this reason, various libraries
have emerged to simplify different tasks such as working with the DOM.
One of the most famous of these libraries is jQuery, which even today is
part of every web developer's toolbox.

10

Probably one of the best-known JavaScript libraries is the jQuery library (https://
[Link]), which, in part, considerably simplifies working with JavaScript. Although
many things are now also possible with standard methods of the DOM API, jQuery is
still a library to be taken seriously. This chapter provides an overview of using jQuery,
including how to simplify accessing and manipulating the DOM, working with events,
and formulating Ajax requests.

Note
The jQuery library is so extensive that we can't cover all its aspects in one chapter.
Instead, we’ll offer a selection of topics that are representative and give a good intro-
duction to the library. Also, we won’t discuss the selected topics in great detail but will
describe the code examples relatively concisely (we’re assuming that you’ve already
acquired the necessary basic knowledge, such as DOM processing, events, Ajax, and so
on, throughout the preceding chapters).

10.1 Introduction
As you’ve seen in the previous chapters, there are differences between different brows-
ers with regard to DOM manipulation, event processing, and Ajax. The jQuery library
abstracts such browser-specific details and provides a unified interface, and not only
for the aforementioned topics. So essentially, jQuery has the following advantages:
쐍 Simplified working with the DOM
jQuery simplifies access to elements of the DOM tree by providing various helper
methods. In Section 10.2, we discuss this topic in more detail. By the way: standard
methods of the current DOM API, like querySelector() and querySelectorAll()
(which are not available in older browsers), are based on ideas from jQuery.

555
10 Simplifying Tasks with jQuery 10.1 Introduction

쐍 Simplified working with events


jQuery simplifies working with events and provides helper methods for this pur- Minified Versions versus Nonminified Versions
pose, which we’ll introduce in Section 10.3. Most libraries offer both a normal (nonminified) version and a minified version for
쐍 Simplified phrasing of Ajax requests download. In the latter, spaces and often comments within the code are removed, for
jQuery simplifies the phrasing of Ajax requests—again, by hiding browser-specific example, and much more is optimized to reduce the file size and thus reduce down-
details. We’ll present the corresponding helper methods in Section 10.4. load time. Consequently, minified versions of libraries are suitable for use in a produc-
tion system. The nonminified version is actually only suitable if you also want to take a
look at the corresponding library during development—during debugging, for exam-
jQuery Isn’t Always Necessary ple.
Although jQuery is a really powerful library, you shouldn’t make the mistake of equat-
ing jQuery with JavaScript and first learning jQuery and then the JavaScript language.
jQuery can certainly be of support in many cases, but often the use of the library isn’t 10.1.2 Embedding jQuery via a Content Delivery Network
even necessary because you can already solve the corresponding tasks with pure Java- 10
If you download jQuery as described and embed it as a local dependency in your web
Script code or even other, leaner libraries. Websites like You Might Not Need jQuery
page and then load your website onto a server, you must also load jQuery onto the
([Link] demonstrate this with various examples.
appropriate server. Alternatively, you have the option of integrating jQuery via a con-
tent delivery network (CDN; see note box). For jQuery, the corresponding URL (for the
current version of the library) is [Link] (see Listing
Tip
10.2).
In principle, it's not bad for a JavaScript developer to both be able to use libraries like
jQuery and have a firm grasp of the basic language concepts as well. <!DOCTYPE html>
<html>
<head lang="en">
<title>jQuery example</title>
10.1.1 Embedding jQuery
<link rel="stylesheet" href="styles/[Link]" type="text/css">
The jQuery library can be embedded in several ways. At [Link] </head>
you can download the current version of the library. Besides the "normal" version, a <body>
minified (i.e., compressed) version is available for download, which is as small as possi- <script src="[Link]
ble in terms of file size. After you’ve downloaded the file, you can include it as usual via <script src="scripts/[Link]"></script>
the <script> element (see Listing 10.1). </body>
</html>
<!DOCTYPE html>
<html> Listing 10.2 Embedding jQuery via a Content Delivery Network
<head lang="en">
<title>jQuery example</title>
<link rel="stylesheet" href="styles/[Link]" type="text/css"> Content Delivery Network
</head> A content delivery network (also known as a content distribution network) is a network
<body> of servers connected via the internet that distribute requests so that they can be
<script src="scripts/[Link]"></script> answered as quickly as possible. Typically, the geographical location of a request plays
<script src="scripts/[Link]"></script> a major role: for example, if a user from Germany accesses your web page and you
</body> have embedded jQuery there via a CDN URL ([Link] the correspond-
</html> ing code is sent to the user from a server in Germany. A user accessing your web page
Listing 10.1 Embedding a Downloaded Version of jQuery from the US, on the other hand, is served by a server located there.

556 557
10 Simplifying Tasks with jQuery 10.1 Introduction

10.1.3 Using jQuery


Note
The core of jQuery is the jQuery() function or the equivalent shortcut function $()
(called the jQuery method ahead). This function can be called with various arguments In all cases shown, the return value of the jQuery method is an object that adds addi-
tional functionality, the jQuery object, to the corresponding elements. This object con-
(see [Link] for details), three forms of which are used particu-
tains references to one or more nodes of the DOM tree, hereafter referred to as selected
larly frequently:
nodes or selected elements.
쐍 Call with CSS selector
In this case, you pass a selector to the jQuery method (similar to the CSS selectors,
but more about that in a moment) and receive an object as the return value that con- 10.1.4 Simplifying Tasks with jQuery
tains the elements of the web page that match the selector. Examples of this are
The fact that jQuery simplifies working with the DOM is best demonstrated using an
shown in Listing 10.3 and Listing 10.4. The object returned by the method represents
example. Suppose you have an HTML list in which each list entry contains a URL (as
a so-called wrapper object (called the jQuery object ahead) for the corresponding ele-
text, not as a link), and you'd like to use JavaScript to create real links from the URLs at 10
ments and provides various methods for these elements (more on this later).
runtime. In other words: The text content of the list entries is to be converted into <a>
const selectedElements = jQuery('body > div > span'); elements.
Listing 10.3 The jQuery() Function Using pure JavaScript, you would probably proceed as shown in Listing 10.7. First, the
appropriate <li> elements must be selected (here, for simplicity, all <li> elements of
const selectedElements = $('body > div > span');
the entire web page). Then, in each case, the text content must be extracted and
Listing 10.4 The More Common Shortcut Function, $() removed, and a new <a> element must be created, its href attribute and text content
must be set, and the element must be added to the <li> element as a child element.
쐍 Call with nodes from the DOM tree
As an alternative to calling the jQuery method with a selector, it can also be called 'use strict';
with a node of the DOM tree or with the corresponding JavaScript object represent- function init() {
ing the respective node. Here as well, the jQuery object represents a wrapper object const listItems = [Link]('li');
around the passed node and provides additional methods. For example, to define an for(let i=0; i<[Link]; i++) {
event listener that is called when the document object is fully loaded, proceed as in const listItem = listItems[i];
Listing 10.5. The ready() method doesn’t exist for the document object but is provided const url = [Link];
indirectly by the jQuery object (see also Section 10.3.2). [Link] = '';
const link = [Link]('a');
$(document).ready(() => { [Link]('href', url);
[Link]('Web page loaded'); const linkText = [Link](url);
}); [Link](linkText);
Listing 10.5 Calling the jQuery Method with a Node from the DOM Tree [Link](link);
}
쐍 Call with HTML string }
You can also use the jQuery method to create new elements. To do this, simply pass [Link]('DOMContentLoaded', init);
the appropriate HTML code for the element you want to create to the method as a
Listing 10.7 Creating Links Using Pure JavaScript
string, as shown in Listing 10.6.

const newElement = $('<div>New element</div>'); Not exactly little code for actually a trivial task. And it doesn't get any better if you use
the innerHTML property instead of the createElement(), setAttribute(), and createText-
Listing 10.6 Calling the jQuery Method with an HTML String
Node() DOM methods, as shown in Listing 10.8. This code also looks relatively cluttered
and cobbled together.

558 559
10 Simplifying Tasks with jQuery 10.2 Working with the DOM

'use strict'; modify, or add elements, for example. Even today, jQuery supports you in the follow-
function init() { ing tasks, among others:
const listItems = [Link]('li');
쐍 Selection of elements (Section 10.2.1)
for(let i=0; i<[Link]; i++) {
listItems[i].innerHTML = '<a href="' 쐍 Accessing and modifying content (Section 10.2.2)
+ listItems[i].textContent + '">' 쐍 Filtering selected elements (Section 10.2.3)
+ listItems[i].textContent + '</a>'; 쐍 Accessing attributes (Section 10.2.4)
}
쐍 Accessing CSS properties (Section 10.2.5)
}
[Link]('DOMContentLoaded', init); 쐍 Navigating between elements (Section 10.2.6)
쐍 Using effects (Section 10.2.7)
Listing 10.8 Creating Links Using innerHTML

10
With jQuery, things get a little more elegant, to say the least. The corresponding code is 10.2.1 Selecting Elements
shown in Listing 10.9. Here the wrapInner() method comes into play, which is made
Using jQuery, elements can be selected using CSS-like selectors. These selectors can be
available to the selected elements by the jQuery object. This method wraps the con-
divided into the following groups:
tents of the selected elements with the HTML code returned by the passed function in
the example. Much simpler than the previous code! 쐍 Basic selectors
Essential selectors that you already know from CSS (see Table 10.1)
'use strict';
쐍 Hierarchy selectors
function init() {
Selectors involving the hierarchy of elements (see Table 10.2), also already known
$('li').wrapInner(
from CSS
function() {
return '<a href="' + [Link] + '"></a>' 쐍 Basic filter selectors
} Selectors that allow you to more specifically filter individual elements, not all of
); which exist in CSS (see Table 10.3)
} 쐍 Content filter selectors
$(document).ready(init) Selectors that include the content of elements (see Table 10.4)
Listing 10.9 Creating Links Using jQuery 쐍 Visibility filter selectors
Selectors involving the visibility of elements (see Table 10.5)
쐍 Attribute filter selectors
jQuery Plug-ins Selectors that include the attributes of elements (see Table 10.6)
By the way, if you don't find a functionality within jQuery, there are thousands of plug-
쐍 Form filter selectors
ins available on the internet. A very good overview is given by the official jQuery regis-
Selectors that are specifically useful for selecting form elements (see Table 10.7)
try at [Link]
쐍 Child filter selectors
Selectors for selecting child elements (see Table 10.8)

10.2 Working with the DOM Selector Description

Working with the DOM wasn’t always as comfortable as it is now thanks to methods * Elements with any element name
like querySelector() and querySelectorAll(). For a long time, jQuery was the first elementName Elements of type elementName
choice when it came to processing the DOM in a relatively simple way—to select,
Table 10.1 Basic Selectors in jQuery

560 561
10 Simplifying Tasks with jQuery 10.2 Working with the DOM

Selector Description Selector Description

#id Element with the ID id :contains() Selects all elements that contain the passed text

.class Elements of the class class :empty Selects all elements that have no child elements or child nodes

selektor1, selector2 Elements that match either the selector1 selector or the selec- :has() Selects all elements that contain at least one element that
tor2 selector matches the passed selector

Table 10.1 Basic Selectors in jQuery (Cont.) :parent Selects all elements that have at least one child node

Table 10.4 Content Filter Selectors in jQuery


Selector Description

element1 element2 All elements of type element2 that are inside an element of type Selector Description
element1
10
:hidden Selects all elements that are not visible
element1 > element2 All elements of type element2 that are direct child elements of an
element of type element1 :visible Selects all visible elements

element1 + element2 All elements of type element2 that directly follow an element of Table 10.5 Visibility Filter Selectors in jQuery
type element1

element1 ~ element2 All elements of type element2 that follow an element of type Selector Description
element1
[name|= "value"] Selects elements with the attribute name for which the values are
Table 10.2 Hierarchy Selectors in jQuery a series of values separated by minus signs and where the first
value is value

Selector Description [name*= "value"] Selects elements with the attribute name, the value of which con-
tains value as a substring
:animated Selects elements that are currently used within an animation.
[name~= "value"] Selects elements with the attribute name, the value of which is a
:header Selects all heading elements—that is, <h1>, <h2>, <h3>, <h4>, list of values, one of which is equal to value
<h5>, and <h6>.
[name$= "value"] Selects elements with the attribute name, the value of which ends
:lang() Selects all elements for the passed language. with value

:not() Selects all elements that do not match the passed selector. [name= "value"] Selects elements with the attribute name that has the value value

:root Selects the root element (not the document node)—that is, the [name!= "value"] Selects elements with the attribute name that do not have the
<html> element. value value

:target Selects the element identified by the fragment ID of the corre- [name^= "value"] Selects elements with the attribute name, the value of which
sponding URL. For example, if the URL is [Link] javas- begins with value
[Link]#jquery, then $(':target') will select the
element with the ID jquery. [name] Selects elements with the attribute name

[name= "value"] Selects elements with the attribute name having the value value
Table 10.3 Basic Filter Selectors in jQuery
[name2= "value2"] and with the attribute name2 having the value value2

Table 10.6 Attribute Filter Selectors in jQuery

562 563
10 Simplifying Tasks with jQuery 10.2 Working with the DOM

Selector Description Selector Description

:button Selects all buttons :nth-of-type() Selects the nth element of a given type

:checkbox Selects all checkboxes :nth-last-of-type() Selects the nth element of a given type, counting from the end

:checked Selects all selected or activated elements :only-child Selects elements that are the only child element of their parent
element
:disabled Selects all disabled elements
:only-of-type() Selects elements that are the only child element of their parent
:enabled Selects all activated elements element of a given type
:focus Selects all elements that have the focus
Table 10.8 Child Filter Selectors in jQuery (Cont.)
:file Selects all file input fields
You can find some examples of using these selectors in Listing 10.10, and complete lists 10
:image Selects all elements with the attribute type having the value
image of all corresponding selectors can be found in the tables ahead.

:input Selects all input fields $(document).ready(() => {


const inputElements = $('input'); // all <input> elements
:password Selects all password fields const john = $('#john'); // element with the ID "john"
const oddElements = $('.odd'); // elements of the class "odd"
:radio Selects all radio buttons
const elements = $('td, th'); // all <td>- und <th> elements
:reset Selects all elements with the attribute type having the value const inputJohn = $('input[name="john"]'); // <input> elements the
reset // name attribute of which
:selected Selects all selected elements // has the value "john"
const oddRows = $('tr').odd()); // all "odd" <tr> elements
:submit Selects all elements with the attribute type having the value sub- const evenRows = $('tr').even(); // all "even" <tr> elements
mit const listItemsAtIndex = $('li:eq(2)'); // all <li> elements at index 2
:text Selects all text input fields const allOthers = $(':not(li)'); // all elements other than <li>
const notExample = $(':not(.example)'); // all elements without the CSS
Table 10.7 Form Filter Selectors in jQuery // class "example"
});

Selector Description Listing 10.10 A Few Examples of Using Selectors

:first-child Selects the first child element

:first-of-type Selects the first element of a given type Note


Some selectors such as :odd (for selecting all "odd" elements), :even (for selecting all
:last-child Selects the last child element
"even" elements), :first (for selecting the first elements), and :last (for selecting the
:last-of-type Selects the last element of a given type last elements) are deprecated since jQuery 3.4. Instead, you should first select the ele-
ments using the appropriate selector and apply the odd(), even(), first(), and last()
:nth-child() Selects the nth child element
methods on the result set (see Listing 10.10 for the use of odd() and even()).
:nth-last-child() Selects the nth child element, counting from the end

Table 10.8 Child Filter Selectors in jQuery

564 565
10 Simplifying Tasks with jQuery 10.2 Working with the DOM

Combination of Selectors
<li>List entry</li> <li>List entry</li> <li>List entry</li>
The individual selectors naturally can be combined with each other, as you know from
CSS.

prepend() append()
10.2.2 Accessing and Modifying Content
After you’ve selected elements via the jQuery method using the selectors presented in before() after()
the previous section, the jQuery object provides various methods for the selected ele-
ments to access and modify the content. These include but are not limited to the fol- Figure 10.1 The Different Methods for Adding Content inside and outside Elements
lowing:
쐍 Accessing and modifying HTML and text content (see Table 10.9) Method Description 10
쐍 Adding content within an element (see Table 10.10 and Figure 10.1) after() Adds content after each of the selected elements: $(a).after(b)
쐍 Adding content outside an element (see Table 10.11 and Figure 10.1) inserts content b after element a (see Figure 10.1).

쐍 Adding content around an element (see Table 10.12) before() Adds content before each of the selected elements: $(a).before(b)
쐍 Replacing content (see Table 10.13) inserts content b before element a (see Figure 10.1).

쐍 Removing content (see Table 10.14) insertAfter() Opposite of after(); that is, $(a).insertAfter(b) inserts element a
after element b.
Method Description
insertBefore() Opposite of before(); that is, $(a).insertBefore(b) inserts element
html() Without an argument, this method returns the HTML content of an ele- a before element b.
ment. With an argument, this method sets the HTML content of an ele-
ment. Table 10.11 Methods for Adding Content outside an Element

text() Without an argument, this method returns the text content of an ele-
ment. With an argument, this method sets the text content of an ele- Method Description
ment.
clone() Creates a copy of the selected elements. More precisely, a so-called deep
copy is created, which also copies child elements of the selected ele-
Table 10.9 Methods for Retrieving and Defining Content
ments.

wrap() Adds new content around each of the selected elements.


Method Description
wrapAll() Adds new content around all selected elements.
append() Adds content to the end of the selected elements: $(a).append(b)
adds content b to the end of element a (see Figure 10.1). wrapInner() Adds new content around the content of each of the selected elements.

appendTo() Opposite of append(); that is, $(a).appendTo(b) adds element a as Table 10.12 Methods for Adding Content around an Element
content to the end of element b.

prepend() Inserts content at the beginning of the selected elements: $(a).pre-


Method Description
pend(b) adds content b to the beginning of element a (see Figure 10.1).
replaceWith() Replaces the selected elements with new content: $(a).replace-
prependTo() Opposite of prepend(); that is, $(a).prependTo(b) adds element a as
With(b) replaces element a with content b.
content to the beginning of element b.
Table 10.13 Methods for Replacing Content
Table 10.10 Methods for Adding Content within an Element

566 567
10 Simplifying Tasks with jQuery 10.2 Working with the DOM

// Add new content after each


Method Description
// <div> element with the CSS class "example"
replaceAll() Opposite of replaceWith(); that is, $(a).replaceAll(b) replaces all $('[Link]').after('<p>Example</p>');
elements selected by selector b with the content in a.
// Add new content before each
Table 10.13 Methods for Replacing Content (Cont.)
// <div> element with the CSS class "example"
$('[Link]').before('<p>Example</p>');
Method Description
Listing 10.11 Some Examples of Changing and Adding Content
detach() Removes the selected elements from the DOM tree but retains refer-
ences to the removed elements so that they can be reincorporated into
the DOM tree at a later time 10.2.3 Filtering Selected Elements

empty() Removes all child nodes from the selected elements The jQuery object also provides various methods for the selected elements, which you
10
can use to further narrow down the currently selected elements (see Table 10.15). Some
remove() Removes the selected elements from the DOM tree examples are shown in Listing 10.12: for example, the eq() method limits the selection
unwrap() Removes the parent element from each of the selected elements to the element at index 2 (i.e., the third <li> element in the example); the first() and
last() methods let you select the first and last of the currently selected elements,
Table 10.14 Methods for Removing Content respectively; the filter() method limits the selection to the specified selector; and the
not() method limits the selection to the elements that do not match the specified
Some examples of these methods are shown in Listing 10.11. For example, you can use selector. You can also use the has() method to select the elements that have at least one
the html() method to access the HTML content, the text() method to access the text child element that matches the given selector. Figure 10.2 illustrates the filter methods
content (both read and write access), append() to append new content to the existing shown in Listing 10.12.
content of the selected elements, prepend() to insert content before the existing con-
// Selection of the third <li> element
tent, after() to append new content to the selected elements, and before() to insert
$('li').eq(2);
content before the selected elements.
// Selection of the first <li> element
// Add new HTML content $('li').first();
$('#main').html('<div>New content</div>'); // Selection of <li> elements that have the CSS class ".selected"
// Access the HTML content $('li').filter('.selected');
const htmlContent = $('#main').html(); // Selection of all <li> elements that contain a <ul> element
$('li').has('ul');
// Add new text content // Selection of all elements that have the CSS class ".selected"
$('#main').text('New text content'); $('li').has('.selected');
// Access the text content // Selection of the last <li> element
const textContent = $('#main').text(); $('li').last();
// Selection of all class attributes of the <li> elements
// Add new content after the $('li').map(() => { [Link] });
// existing content of each <div> element // Selection of all <li> elements that do not have the CSS class ".selected"
// with the CSS class "example" $('li').not('.selected');
$('[Link]').append('<p>Example</p>'); // Selection of the first two <li> elements
$('li').slice(0, 2);
// Add new content before the
Listing 10.12 Usage of Different Filter Methods
// existing content of each <div> element
// with the CSS class "example"
$('[Link]').prepend('<p>Example</p>');

568 569
10 Simplifying Tasks with jQuery 10.2 Working with the DOM

Method Description
html
is() Checks if at least one of the selected elements (1) matches the passed selec-
tor, (2) returns true for the passed filter function, (3) is contained in the
… body
passed jQuery object, or (4) is one of the elements passed as parameter

last() Reduces the selected elements to the last element


ul
not() Reduces the selected elements to those that (1) do not match the passed
$('li').not('.selected');
$('li').first(); $('li').last(); selector, (2) do not match the passed filter function, or (3) are not contained
$('li').slice(0, 2); $('li').eq(2); $('li').not('.selected');
$('li').slice(0, 2); $('li').not('.selected'); in the passed jQuery object
$('li').has('ul');

slice() Reduces the selected elements to a subset defined by start and end index
li li li li li
Table 10.15 Methods for Filtering (Cont.) 10
class="selected" class="selected"

10.2.4 Accessing Attributes


ul
The jQuery object also provides some methods to access HTML attributes (see Table
$('li').not('.selected'); $('li').not('.selected'); $('li').not('.selected'); 10.16). The attr() method can be used to determine or reset values of attributes, as
$('li').slice(0, 2); $('li').slice(0, 2); $('li').eq(2);
shown in Listing 10.13: if you pass the name of an attribute to the method, the method
returns the corresponding value of the attribute; if, on the other hand, you pass
li li li another string as the second argument to the method, this string is used as the new
value for the attribute.
Figure 10.2 Narrowing Down Elements via jQuery Filter Methods
Alternatively, you can pass an object to the method in order to add several attributes in
one go. In this case, the object's property names are used as names for the attributes,
Method Description and the object property values are used as values for the attributes.
add() Adds new elements to a selection of elements To delete attributes, however, use the removeAttr() method. For adding and removing
CSS classes, the methods addClass() and removeClass() are available. However, these
addBack() Adds a previous selection to the current selection of elements
two methods are actually redundant—at least for newer browsers that support the
eq() Reduces the selected elements to one element at a given index classList property, which provide equivalent functionality via the add() and remove()
filter() Reduces the selected elements to those elements (1) that match the passed methods.
selector or (2) for which the passed filter function returns true const element = $('a#main');
find() Selects the child elements of the selected elements that (1) match the // Read access to the "href" attribute of the element
passed selector, (2) are contained in the passed jQuery object, or (3) are equal const href = [Link]('href');
to the passed element // Write access to the "href" attribute of the element
[Link]('href', '[Link]');
first() Reduces the selected elements to the first element
// Alternative write access via configuration object
has() Reduces the selected elements to those elements that have a child element [Link]({
that (1) matches the passed selector or (2) is equal to the passed element href: '[Link]',
target: '_blank'
Table 10.15 Methods for Filtering });
// Remove the "href" attribute from the element
[Link]('href');

570 571
10 Simplifying Tasks with jQuery 10.2 Working with the DOM

// Add a CSS class const properties = $('body').css(['color', 'background-color']);


[Link]('highlighted'); // Set the background color of the <body> element
// Remove a CSS class $('body').css('background-color', 'blue');
[Link]('highlighted'); // Set the foreground color and the background color of the <body> element
$('body').css({
Listing 10.13 Access to Attributes and CSS Classes
'color': 'white',
'background-color': 'blue'
Method Description });

attr() With one argument, this method returns the value for an attribute (e.g., Listing 10.14 Accessing CSS Properties
$(‘a#main’).attr(‘href’)). With two arguments, this method sets
the value of an attribute (e.g., $('a#main').attr('href',
'[Link]')). 10.2.6 Navigating between Elements
10
removeAttr() Removes an attribute from an element, e.g., $('a#main').removeAttr Starting from a selection of elements stored in a jQuery object, you can use the meth-
('href')). ods presented ahead to find elements that have a specific relationship to these ele-
ments, such as parent elements, sibling elements, and child elements. Some examples
addClass() Adds a new CSS class to the values in the class attribute. In newer
are shown in Listing 10.15. The corresponding descriptions of the methods can be found
browsers, this is possible without jQuery thanks to the standardized
classList property and its add() method. in Table 10.17.

removeClass() Removes a CSS class from the values in the class attribute. This too is // Child elements
possible in newer browsers without jQuery thanks to the classList // Selection of all child elements of <ul>
property and its remove() method. However, the removeClass() const listItems = $('ul').children();
method can alternatively be passed a function that returns a comma- // Selection of the next link within <ul>
separated list of CSS classes. This functionality isn’t possible via the const closestLink = $('ul').closest('a');
remove() method of the classList property.
// Sibling elements
toggleClass() Toggles a CSS class: if the element has the passed class, the class will be
removed, and if the element doesn’t have the passed class, the class will // Selection of the next sibling element
be added. const nextSibling = $('ul').next();
// Selection of the next link element
Table 10.16 Methods for Accessing Attributes and CSS Classes const nextSiblingLink = $('ul').next('a');
// Selection of all next sibling elements
const nextSiblings = $('ul').nextAll();
10.2.5 Accessing CSS Properties
// Selection of all next link elements
To access CSS properties, jQuery provides the css() method. Like other methods, such const nextSiblingLinks = $('div').nextAll('a');
as html(), text(), and attr(), this method can be used to both read and set values. For // Selection of all next sibling elements up to the specified element
the former, pass the method the name of the CSS property of which the value is to be const nextSiblingsUntil = $('div').nextUntil('a');
read; for the latter, specify the value to be set as the second parameter. // Selection of the previous sibling element
const previousSibling = $('ul').prev();
Alternatively, as with the attr() method, an object can be passed as an argument, and
// Selection of all previous sibling elements
the respective properties are then used as CSS properties. In addition, you can also pass
const previousSiblings = $('ul').prevAll();
an array of strings as an argument to read the values of several CSS properties in one
// Selection of all previous sibling elements up to the specified element
step. Some examples are shown in Listing 10.14.
const previousSiblingsUntil = $('div').prevUntil('a');
// Read the background color of the <body> element // Selection of all sibling elements
const backgroundColor = $('body').css('background-color'); const siblings = $('div').siblings();
// Read the foreground color and the background color of the <body> element

572 573
10 Simplifying Tasks with jQuery 10.2 Working with the DOM

// Parent elements
Method Description
// Selection of the parent element
const parent = $('ul').parent(); prevUntil() Selects all previous sibling elements of the selected elements. If a
// Selection of all parent elements selector is passed, the previous sibling elements are selected up to the
const parents = $('ul').parents(); sibling element that matches this selector.
// Selection of all parent elements up to the specified element siblings() Selects all sibling elements of the selected elements. If a selector is
const parentsUntil = $('ul').parentsUntil('div'); passed, the sibling elements that match this selector are selected.

Listing 10.15 Various Examples of Navigating between Elements Table 10.17 Methods for Navigating the DOM Tree (Cont.)

Method Description
10.2.7 Using Effects and Animations
children() Selects the child elements of the selected elements. Optionally, a selec-
Effects such as fading in or out elements of a web page were not always as easy to imple- 10
tor can be passed--in that case only those child elements are selected
ment as they are now with the help of CSS3 animations. It’s little wonder then that
to which this selector applies..
jQuery offers several methods for this as well, the most important of which are shown
closest() Selects the first element of the selected elements that matches the in Table 10.18. For example, with fadeIn(), fadeOut(), and fadeToggle(), it’s possible to
selector passed as a parameter or for which one of the parent ele- fade the selected elements in and out, and slideDown(), slideUp(), and slideToggle()
ments matches the selector.
enable you to slide the selected elements in and out.
next() Selects the next sibling element of the selected elements. If a selector The most flexible option is provided by animate(). This method can be passed—in the
is passed, the next sibling element that matches this selector is
form of a configuration object—various CSS properties to be animated, the speed or
selected.
duration of the animation (either as a string, such as one of the values fast or slow, or
nextAll() Selects all next sibling elements of the selected elements. If a selector as a numeric value specifying the duration in milliseconds), an easing function (which
is passed, the next sibling elements that match this selector are describes how the speed of the animation behaves in relation to the time within the
selected.
animation), and a callback function that’s called when the animation has been fully
nextUntil() Selects all next sibling elements of the selected elements. If a selector executed (see Listing 10.16).
is passed, the next sibling elements are selected up to the sibling ele-
ment that matches this selector. Method Description

parent() Selects the parent element of the selected elements. animate() Enables the animation of CSS properties.

parents() Selects all parent elements preceding in the hierarchy of the selected clearQueue() Removes all animations from the queue that have not yet been exe-
elements. cuted.

parentsUntil() Selects all parent elements preceding in the hierarchy of the selected delay() Delays an animation by a specified number of milliseconds.
elements up to an element that (1) matches the passed selector, (2)
dequeue() Executes the next animation in the queue.
matches the passed element, or (3) is contained in the passed jQuery
object. fadeIn() Fades the selected elements in.

prev() Selects the previous sibling element of the selected elements. If a fadeOut() Fades the selected elements out.
selector is passed, the previous sibling element that matches this
selector is selected. fadeTo() Adjusts the opacity of the selected elements.

prevAll() Selects all previous sibling elements of the selected elements. If a fadeToggle() Fades the selected elements in or out, depending on their state: if an
selector is passed, the previous sibling elements that match this selec- element is visible, it’s faded out, but if it isn’t visible, it’s faded in.
tor are selected.
Table 10.18 Methods for Displaying and Hiding Elements
Table 10.17 Methods for Navigating the DOM Tree

574 575
10 Simplifying Tasks with jQuery 10.3 Responding to Events

We also showed a corresponding browser-independent helper function in Chapter 6.


Method Description
The jQuery library offers a browser-independent solution as well.
finish() Stops the current animation, removes all animations from the queue,
and sets the CSS properties of the selected elements to the target value.
10.3.1 Registering Event Listeners
hide() Hides the selected elements.
jQuery provides several methods to respond to events or register event listeners. So, on
queue() Accesses the animations in the queue.
the one hand, you can use the on() method, which is called on the jQuery object, as
show() Shows the selected elements. shown in Listing 10.17: you pass the name of the event to be responded to as the first
parameter and the event listener in the form of a function as the second parameter.
slideDown() Slides the selected elements down, from top to bottom.
$('#button').on('click', (event) => {
slideToggle() Slides the selected elements in or out, depending on their state: if an
[Link]('Button pressed');
element is visible, it slides out from bottom to the, but if it isn’t visible,
}); 10
it slides in from top to bottom.
Listing 10.17 Registering an Event Listener
slideUp() Slides the selected elements up, from bottom to top.

stop() Stops the current animation.


Note
toggle() Hides or displays the selected elements: if an element is visible, it’s
hidden, but if it isn’t visible, it’s displayed. If the jQuery object contains references to multiple elements, calling an event method
for each element in the selection invokes the corresponding event listener.
Table 10.18 Methods for Displaying and Hiding Elements (Cont.)

As an alternative to the general on() method, jQuery offers various methods named
'use strict';
specifically after the event to be caught, such as the click() method found in Listing
$(document).ready(() => {
10.18. Logically, these event methods don’t need to be passed the name of the respec-
$('main').animate(
tive event as a parameter, but only the event listener.
{ opacity: 0.75 }, // Properties
'fast', // Speed $('#button').click((event) => {
'swing', // Easing [Link]('Button pressed');
() => { });
// Animation completed
Listing 10.18 Registering an Event Listener via the Shorthand Method
}
);
Overall, the event methods can be classified as follows:
});
쐍 General event methods (see Table 10.19)
Listing 10.16 Accessing CSS Properties
쐍 Event methods for handling general events (Section 10.3.2)
쐍 Event methods for handling mouse events (Section 10.3.3)
10.3 Responding to Events 쐍 Event methods for handling keyboard events (Section 10.3.4)
쐍 Event methods for handling form events (Section 10.3.5)
As you recall from Chapter 6, there are several options for catching events. Event han-
dlers are usually available for the corresponding event, and there’s also the possibility
to register several event listeners for one event via the addEventListener() method.
Older versions of Internet Explorer also use the attachEvent() method, which fulfills a
similar task.

576 577
10 Simplifying Tasks with jQuery 10.3 Responding to Events

Method Description Method Description

bind() Adds an event listener for an event. Since jQuery 1.7, however, the resize() Register event listeners that are executed when a resize event occurs.
on() method should be used according to the official documenta-
scroll() Register event listeners that are executed when an element is scrolled.
tion.

delegate() For older jQuery versions, this is the preferred method to add an Table 10.20 Different Methods for Registering Event Listeners (Cont.)
event listener for an event. However, since jQuery 1.7, the on()
method should be used. $(document).ready(() => {
[Link]('Web page loaded');
off() Removes an event listener for an event.
});
on() Adds an event listener for an event.
Listing 10.19 Registering an Event Listener for Loading the Document
one() Adds an event listener that is triggered at most once per event for
10
each selected element.
10.3.3 Responding to Mouse Events
trigger() Runs all event listeners registered for an event.
Table 10.21 shows the methods jQuery uses to register event listeners for mouse events.
triggerHandler() Like the trigger() method, but doesn’t perform the default behav- They basically correspond to the events you already know from Chapter 6: click() and
ior for an event (such as submitting a form). dbclick() for mouse clicks; focusin() and focusout() for focusing elements; and mouse-
unbind() Removes an event listener for an event. Since jQuery 1.7, however, down(), mouseenter(), mouseleave(), mousemove(), mouseout(), mouseover(), and mouseup()
the off() method should be used according to the official docu- for mouse movements over elements.
mentation.
Method Description
undelegate() For older jQuery versions, this is the preferred method to remove an
event listener for an event. However, since jQuery 1.7, the off() click() Register event listeners that are executed when the mouse is clicked
method should be used.
dblclick() Register event listeners that are executed when the mouse is double-
Table 10.19 Methods for Managing Event Handlers clicked

focusin() Register event listeners that are executed when an element receives
focus
10.3.2 Responding to General Events
focusout() Register event listeners that are executed when an element loses focus
Table 10.20 contains some methods for registering event listeners for general events:
error() enables you to register event listeners that are triggered when an error event is hover() Register event listeners that are executed when the mouse pointer hov-
raised on the selected elements, event listeners registered via ready() are called as soon ers over an element
as the corresponding elements have been loaded (see Listing 10.19), event listeners reg-
mousedown() Register event listeners that are executed when the mouse pointer is
istered via resize() are called whenever a resize event occurs for the elements, and over an element and the mouse button is pressed
event listeners registered via scroll() are called whenever a scroll event occurs for the
elements. mouseenter() Register event listeners that are executed when the mouse pointer
enters an element
Method Description
mouseleave() Register event listeners that are executed when the mouse pointer leaves
error() Register event listeners that are executed when an error event occurs. an element

ready() Register event listeners that are executed when the DOM or the element mousemove() Register event listeners that are triggered when the mouse moves over
passed to the method is fully loaded. an element

Table 10.20 Different Methods for Registering Event Listeners Table 10.21 Methods for Handling Mouse Events

578 579
10 Simplifying Tasks with jQuery 10.3 Responding to Events

Method Description
10.3.4 Responding to Keyboard Events
For registering event listeners for keyboard events, the methods listed in Table 10.22
mouseout() Register event listeners that are executed when the mouse pointer leaves
an element are available: keydown(), keyup(), and keypress() for registering event listeners that are
triggered when a key is pressed or released. Again, all of this should be familiar from
mouseover() Register event listeners that are executed when the mouse pointer Chapter 6.
enters an element
Method Description
mouseup() Register event listeners that are executed when the mouse pointer is
over an element and the mouse button is released keydown() Register event listeners that are executed when a key on the keyboard is
pressed. If a key is pressed for a longer time, the event listener is executed
Table 10.21 Methods for Handling Mouse Events (Cont.) several times.

An example is shown in Listing 10.20. keypress() Register event listeners that are executed when a key on the keyboard is
pressed. 10
$('button#target').click((event) => {
keyup() Register event listeners that are executed when a key on the keyboard is
[Link]('Button was pressed');
released.
});

Listing 10.20 Registering an Event Listener for a Mouse Event Table 10.22 Methods for Handling Keyboard Events

By the way, it’s also possible to use the event methods not for registering event listen- An example of using these methods is shown in Listing 10.22. This nicely illustrates
ers, but for triggering events. To do this, simply call the corresponding method without how the individual event methods (or all jQuery methods in general) can be used one
any arguments. In Listing 10.21, for example, within the second event listener (regis- after the other.
tered on the <button> element with the ID target2), the click event is triggered for the $('input#username')
<button> element with the ID target. .keypress((event) => {
$('button#target').click((event) => { [Link]('Key for entering username pressed.');
[Link]('Button was pressed'); })
}); .keydown((event) => {
$('button#target2').click((event) => { [Link]('Key is pressed.');
$('button#target').click(); })
}); .keyup((event) => {
[Link]('Key for entering username released.');
Listing 10.21 Triggering an Event });

Listing 10.22 Registering Different Event Listeners for Keyboard Events


Note
Most methods in jQuery can be called with a different number of arguments, and each
Fluent API
has different functions. For example, as shown earlier in this chapter, you can use the
attr() method to both read and write HTML attributes or, as just shown, you can use When an API allows you to call a method directly on the return value of a method, as in
the event methods to both register event listeners and trigger events. Listing 10.22, it is also called a fluent API.

10.3.5 Responding to Form Events


The methods listed in Table 10.23 for registering event listeners related to form events
should also be essentially familiar from Chapter 6: blur() and focus() for registering

580 581
10 Simplifying Tasks with jQuery 10.3 Responding to Events

event listeners that are triggered when a form field loses or receives focus, change()
Property/Method Description
when the value of a form field changes, select() when a specific value is selected for a
form field, and submit() when a form is submitted. currentTarget Contains the current element during the bubbling
phase
Method Description
data Contains an optional data object passed to the
blur() Register event listeners that are executed when a form field loses focus event method

change() Register event listeners that are executed when the selected value of a selec- delegateTarget Contains the element on which the event listener
tion list, a checkbox, or a group of radio buttons has been changed was registered

focus() Register event listeners that are executed when a form field receives focus isDefaultPrevented() Indicates whether preventDefault() was called
on the event object
select() Register event listeners that are executed when the text of an input field
(<input> element of the text type) or a text input area (<textarea> element) isImmediatePropagationStopped() Indicates whether stopImmediatePropagation()
10
is selected was called on the event object

submit() Register event listeners that are executed when a form is submitted isPropagationStopped() Indicates whether stopPropagation() was called
on the event object
Table 10.23 Methods for Handling Form Events
metaKey Contains an indication of whether the so-called
meta key (for Mac keyboards, the (cmd) key; for
Some examples are shown in Listing 10.23. Windows keyboards, the (Windows) key) was
$('input#username') pressed while the event was triggered.
.focus((event) => { namespace Contains the namespace of the event
[Link]('Input field focused.');
}) pageX Contains the mouse position relative to the left
.blur((event) => { edge of the document

[Link]('Input field no longer focused.'); pageY Contains the mouse position relative to the top of
}) the document
.change((event) => {
preventDefault() Prevents the default action for an event from being
[Link]('Text changed.');
executed
})
.select((event) => { relatedTarget For an element for which an event was triggered,
[Link]('Text selected.'); contains the element directly related to the event
}); (e.g., in the case of a mouseout event, the element
on which the mouseover event was triggered by the
Listing 10.23 Registering Different Event Listeners for Form Events same user action)

result Contains the result of an event listener previously


10.3.6 Accessing Information from Events triggered for an event

The event object, which is available as a parameter within each event listener, contains stopImmediatePropagation() Immediately prevents the event from rising further
different information and provides different methods, as shown in Table 10.24. Basi- during the bubbling phase
cally, this is the information also contained in the standard event object, as discussed
stopPropagation() Prevents the event from rising further during the
in Chapter 6, supplemented by a few more details. But again, jQuery hides the browser-
bubbling phase
specific details, allowing for browser-independent use.
Table 10.24 Properties and Methods of the Event Object

582 583
10 Simplifying Tasks with jQuery 10.4 Creating Ajax Requests

selection of elements, as has been the case so far in this chapter, but directly on the
Property/Method Description
$ object. Therefore, we call these methods global jQuery methods ahead.
target Contains the element that triggered the event
Method Description
timeStamp Contains a timestamp indicating the time when
the event was triggered $.ajax() Performs an asynchronous HTTP request

type Contains the type of the event $.get() Performs an HTTP request using the HTTP GET method

which In the case of mouse or keyboard events, contains $.getJSON() Performs an HTTP GET request to load JSON data from a server
the mouse button or key on the keyboard that was
pressed $.getScript() Performs an HTTP GET request to load JavaScript data from a server and
execute it directly
Table 10.24 Properties and Methods of the Event Object (Cont.)
load() Performs an HTTP GET request to load HTML data from a server and
embed it directly into the selected elements 10
Listing 10.24 shows an example of how you can access this information. Most impor-
tantly, you can also see here that it’s possible to pass an event a data object that you can $.post() Performs an HTTP request using the HTTP POST method

then access within the event listener. Table 10.25 Main Methods for Working with Ajax
$('input').on(
'change, The jQuery global method ajax() (or $.ajax()) allows you to create arbitrary Ajax
{ requests. The configuration object expected by this method gives you the most leeway
value : 4711 // Data object regarding the configuration of a request.
},
The get() and post() methods are used to create GET or POST requests, meaning that you
(event) => {
don't have to worry about specific configurations for these request types, such as spec-
[Link]([Link]); // current element
ifying the HTTP method.
[Link]([Link]); // data object
[Link]([Link]); // property of the data object In addition, special methods are available for loading HTML data (load()), loading JSON
[Link]([Link]); // x position of mouse data (getJSON()), and loading JavaScript files (getScript()).
[Link]([Link]); // y position of mouse Listing 10.25 shows an example of using the ajax() method, which you already know
}
about in principle from Chapter 9: the goal is to load JSON data from the server and
);
dynamically create a table for this data.
Listing 10.24 Accessing the jQuery Event Object The URL for the request is configured via the url property of the configuration object,
the type expected as a response via the dataType property (possibilities include, for
example, json, xml, or html), and the type of the request via the type property. Callback
10.4 Creating Ajax Requests functions for the successful execution of a request or also for errors can be defined via
the success and error properties. Within the success callback function, the response of
Generating Ajax requests is also considerably simplified by jQuery. In this section, we’ll
the server is accessed via the data parameter in the example. Because this is JSON data,
show you how to perform the examples in Chapter 9 for Ajax-based loading of HTML,
it can be processed directly to create the table, as already mentioned.
XML, and JSON data via the appropriate jQuery methods.
'use strict';
$(document).ready(() => {
10.4.1 Creating Ajax Requests $.ajax({
For creating Ajax requests, jQuery provides several methods, listed in Table 10.25. These url: '[Link]',
are methods that—with the exception of the load() method—are called not on a dataType: 'json',
type: 'GET',

584 585
10 Simplifying Tasks with jQuery 10.4 Creating Ajax Requests

success: (data) => { const row = createRow(


const table = initTable(); [Link],
const artists = [Link]; [Link],
for (let i = 0; i < [Link]; i++) { [Link]
const artist = artists[i]; );
const albums = [Link]; $(table).find('tbody').append(row);
for (let j = 0; j < [Link]; j++) { }
const album = albums[j]; }
const row = createRow( $('#artists-container').append(table);
[Link], })
[Link], .fail((jqXHR, errorMessage, error) => {
[Link] });
); }); 10
$(table).find('tbody').append(row);
Listing 10.26 Generating an Ajax Request via the Fluent API
}
}
$('#artists-container').append(table); 10.4.2 Responding to Events
},
For responding to events related to working with Ajax requests, jQuery provides the
error: (jqXHR, errorMessage, error) => {
methods shown in Table 10.26.
}
});
Method Description
});
ajaxComplete() Specify an event listener that is called when an Ajax request completes
Listing 10.25 Generating an Ajax Request
ajaxError() Specify an event listener for errors
As an alternative to specifying the callback functions via the success and error proper-
ajaxSend() Specify an event listener that is called when an Ajax request is sent
ties, you also have the option of defining them via the done() and fail() methods,
which (thanks to jQuery's Fluent API) can be combined directly with calling the ajax() ajaxStart() Specify an event listener that is called when the first Ajax request is
started
method (see Listing 10.26).
ajaxStop() Specify an event listener that is called when all Ajax requests have
'use strict';
completed
$(document).ready(() => {
$.ajax({ ajaxSuccess() Specify an event listener that is called whenever an Ajax request com-
url: '[Link]', pletes successfully
dataType: 'json',
type: 'GET' Table 10.26 Methods for Handling Ajax Events
})
.done((data) => { An example is shown in Listing 10.27. There are two things to keep in mind here: first,
const table = initTable(); the methods are each called on a selection of elements (or the corresponding jQuery
const artists = [Link]; object); second, the event listeners each have a different number of parameters. The
for (let i = 0; i < [Link]; i++) { event listeners for ajaxStart() and ajaxStop() have no parameters at all, the event lis-
const artist = artists[i]; teners for ajaxSend() and ajaxComplete() each get the event object, plus an object rep-
const albums = [Link]; resenting the Ajax request and an object with configurations related to the request. The
for (let j = 0; j < [Link]; j++) { event listeners for the ajaxSuccess() and ajaxError() methods also receive the
const album = albums[j]; response data and the error object, respectively.

586 587
10 Simplifying Tasks with jQuery 10.4 Creating Ajax Requests

$(document) url: name + '.html',


.ajaxStart(() => { dataType: 'html'
[Link]('Request started.'); }).done((data) => {
}) $('#main-content').html(data);
.ajaxSend((event, request, settings) => { });
[Link]('Request sent.'); }
})
Listing 10.28 Loading HTML Data via Ajax
.ajaxSuccess((event, request, settings, data) => {
[Link]('Request completed successfully');
But this process is even easier with the load() method, as shown in Listing 10.29. You
})
can call this method directly on a jQuery object (or the selection of elements it rep-
.ajaxError((event, request, settings, error) => {
[Link]('Error on request: ' + error); resents). As arguments, you pass the URL from which the HTML data should be loaded
}) and optionally a callback function that will be called when the data has been success-
10
.ajaxComplete((event, request, settings) => { fully loaded.
[Link]('Request completed.'); function loadContent(name) {
}) $('#main-content').load(
.ajaxStop(() => { name + '.html',
[Link]('All requests completed.'); (
}); responseText,
Listing 10.27 Registering Different Event Listeners for Ajax Events textStatus,
jqXHRObject
) => {
10.4.3 Loading HTML Data via Ajax [Link]('HTML loaded');
To load HTML data via Ajax, you can proceed as in Listing 10.28 and use the global }
jQuery get() method. The important thing here is that you pass the value html to the );
}
dataType property. You can then use html() in the corresponding callback function to
assign the response data directly to an element as HTML content. Listing 10.29 Alternative Loading of HTML Data via Ajax

'use strict';
$(document).ready(() => {
Sending Additional Data with the Request
const login = $('#login');
const register = $('#register'); You can optionally insert another argument between the URL and the callback func-
[Link]((e) => { tion—namely to define the data to be sent to the server with the request (in the form
[Link](); of a string). This is useful, for example, if the server is to generate either this or that
loadContent('login'); response based on the data.
});
[Link]((e) => {
[Link](); 10.4.4 Loading XML Data via Ajax
loadContent('register'); To load XML data, use the get() method as shown in Listing 10.30, passing the xml value
});
for the dataType property. Within the callback function, the response data is then
});
directly available as XML or as a DOM tree. The best thing about this is that the jQuery
$() method can also use it—for example, to select all <artist> elements using the
function loadContent(name) {
find() method as shown in the listing, to iterate over these elements using each()
$.get({

588 589
10 Simplifying Tasks with jQuery 10.4 Creating Ajax Requests

(another helper method of jQuery, by the way), or to access the text content of the const albums = [Link];
<title> and <year> elements using text(). for (let j = 0; j < [Link]; j++) {
const album = albums[j];
'use strict';
const row = createRow(
$(document).ready(() => {
[Link],
$.get({
[Link],
url: '[Link]',
[Link]
dataType: 'xml'
);
}).done((data) => {
$(table).find('tbody').append(row);
const table = initTable();
}
const artists = $(data).find('artist');
}
[Link]((index, artist) => {
$('#artists-container').append(table);
const albums = $(artist).find('album');
}); 10
[Link]((index, album) => {
});
const row = createRow(
[Link]('name'), Listing 10.31 Loading JSON Data via Ajax
$(album).find('title').text(),
$(album).find('year').text() Alternatively, jQuery provides the getJSON() method, which further simplifies request-
); ing JSON data (see Listing 10.32). As arguments, you pass this method the URL to be
$(table).find('tbody').append(row); requested and a callback function to access the JSON data sent by the server.
});
'use strict';
});
$(document).ready(() => {
$('#artists-container').append(table);
$.getJSON(
});
'[Link]',
});
(
Listing 10.30 Loading XML Data via Ajax data,
textStatus,
jqXHRObject
10.4.5 Loading JSON Data via Ajax
) => {
We showed you how to load JSON data using jQuery at the beginning of Section 10.4.1 // here is the already known content
using the ajax() method. Listing 10.31 shows the equivalent example using the get() }
method. You specify json as the value for the dataType property and can then access the );
JSON data sent by the server in the callback function as usual. });

'use strict'; Listing 10.32 Alternative Loading of JSON Data via Ajax
$(document).ready(() => {
$.get({
url: '[Link]', Sending Additional Data with the Request
dataType: 'json' As you saw with the load() method, you can optionally specify one more argument
}).done((data) => { between the URL and the callback function to define those data that should be sent to
const table = initTable(); the server with the request.
const artists = [Link];
for (let i = 0; i < [Link]; i++) {
const artist = artists[i];

590 591
10 Simplifying Tasks with jQuery 10.5 Summary

10.5 Summary Finally, Table 10.27 compares how different problems can be handled with jQuery and
with pure JavaScript. For more examples, we recommend looking at the [Link]
In this chapter, you learned about the popular jQuery JavaScript library, which simpli- [Link] website mentioned earlier. There you can see very nicely how
fies many things, especially with regard to DOM manipulation, event handling, and the code of both variants is about equally compact, especially in the DOM manipula-
creating Ajax requests. The following list summarizes the most important aspects: tion area. When working with events and with Ajax, the code is still a bit more compact
쐍 jQuery is a library that mainly hides browser-specific details and provides helper with jQuery. In all cases, however, it’s true that jQuery is largely browser-independent,
methods for recurring tasks that can be used across browsers. while this doesn’t always apply to the pure JavaScript variants.
쐍 The linchpin for working with jQuery is the jQuery() or $() method.
Working with the DOM
쐍 Among other things, you can pass a selector, an existing element, or an HTML string
as an argument to this method. Add CSS class jQuery:
$(element).addClass(
쐍 As a return value, the method provides a wrapper object (jQuery object) that extends
newClassName
the corresponding elements by additional methods (jQuery methods). 10
);
쐍 Thus, a jQuery object provides various methods for working with the DOM, includ-
Pure JavaScript:
ing the following:
if ([Link]) {
– Methods to access the content of elements
[Link](newClassName);
– Methods to filter selected elements } else {
– Methods to access attributes [Link] += ' ' + newClassName;
}
– Methods to access CSS properties
– Methods to navigate between elements Access child elements jQuery:

– Methods to animate elements or their CSS properties $(element).children();

쐍 For working with events, jQuery provides several methods to register event listen- Pure JavaScript:
ers, including the following: [Link]
– Methods to register event listeners for general events Iterate over elements jQuery:
– Methods to register event listeners for mouse events $(selector).each(
– Methods to register event listeners for keyboard events (index, element) => {
}
– Methods to register event listeners for form events
);
쐍 Creating Ajax requests is also made easier by a number of helper methods, including
the following: Pure JavaScript:
const elements = [Link](
– A method to create arbitrary Ajax requests
selector
– A method to create GET requests );
– A method to create POST requests [Link](
elements, (element, index) => {
– A method to load HTML content directly into an element via Ajax
}
– A method to load JavaScript files );
– A method to load JSON files
Table 10.27 Comparison between jQuery and Pure JavaScript
쐍 Most helper methods can be used for various purposes; for example, HTML attri-
butes can be both read and written via the attr() method, CSS properties can be read
and written via the css() method, and event listeners can be registered or removed
again via the event methods.

592 593
10 Simplifying Tasks with jQuery 10.5 Summary

Working with the DOM Working with the DOM

Search elements below jQuery: Write text content jQuery:


an element $(element).find( $(element).text(content);
selector
); Pure JavaScript:
[Link] = content;
Pure JavaScript:
[Link]( Next element jQuery:
selector $(element).next();
);
Pure JavaScript:
Search elements jQuery: [Link];
$(selector); 10
Previous element jQuery:
Pure JavaScript: $(element).prev();
[Link](selector);
Pure JavaScript:
Access attributes jQuery: [Link];
$(element).attr(name);
Working with events
Pure JavaScript:
Add event listener jQuery:
[Link](name);
$(element).on(
Read HTML content jQuery: eventName,
$(element).html(); eventHandler
);
Pure JavaScript:
Pure JavaScript:
[Link];
[Link](
Write HTML content jQuery: eventName,
$(element).html(content); eventHandler
);
Pure JavaScript:
Remove event listener jQuery:
[Link] = content;
$(element).off(
Read text content jQuery: eventName,
$(element).text(); eventHandler
);
Pure JavaScript:
Pure JavaScript:
[Link];
[Link](
Table 10.27 Comparison between jQuery and Pure JavaScript (Cont.) eventName,
eventHandler
);

Table 10.27 Comparison between jQuery and Pure JavaScript (Cont.)

594 595
10 Simplifying Tasks with jQuery 10.5 Summary

Working with the DOM Working with the DOM

Execute function when jQuery: Load JSON via Ajax jQuery:


loading the document $(document).ready(() => { $.getJSON(
}); '[Link]',
(data) => {}
Pure JavaScript: );
function ready(callback) {
if ([Link] != 'loading'){ Pure JavaScript:
callback(); fetch('[Link]')
} else { .then(response => [Link]())
[Link]( .then(data => {})
'DOMContentLoaded', .catch(error => {});
callback 10
); Table 10.27 Comparison between jQuery and Pure JavaScript (Cont.)
}
}

Working with Ajax requests

Send GET request jQuery:


$.ajax({
type: 'GET',
url: url,
success: response => {},
error: () => {}
});

Pure JavaScript:
fetch(url)
.then(response => {})
.catch(error => {});

Send POST request jQuery:


$.ajax({
type: 'POST',
url: url,
data: data
});

Pure JavaScript:
fetch('url', {
method: 'POST',
body: data,
})
.then(response => {})
.catch(error => {});

Table 10.27 Comparison between jQuery and Pure JavaScript (Cont.)

596 597
Contents

Book Resources ....................................................................................................................................... 25


Preface ....................................................................................................................................................... 27

1 Basics and Introduction 31

1.1 Programming Basics ............................................................................................................. 31


1.1.1 Communicating with the Computer ............................................................... 32
1.1.2 Programming Languages ..................................................................................... 33
1.1.3 Tools for Program Design .................................................................................... 40
1.2 Introduction to JavaScript ................................................................................................. 46
1.2.1 History ........................................................................................................................ 46
1.2.2 Fields of Application .............................................................................................. 47
1.3 Summary ................................................................................................................................... 53

2 Getting Started 55

2.1 Introduction to JavaScript and Web Development ................................................ 55


2.1.1 The Relationship among HTML, CSS, and JavaScript .................................. 55
2.1.2 The Right Tool for Development ....................................................................... 59
2.2 Integrating JavaScript into a Web Page ...................................................................... 64
2.2.1 Preparing a Suitable Folder Structure ............................................................. 64
2.2.2 Creating a JavaScript File ..................................................................................... 65
2.2.3 Embedding a JavaScript File in an HTML File ................................................ 66
2.2.4 Defining JavaScript Directly within the HTML .............................................. 69
2.2.5 Placement and Execution of the <script> Elements ................................... 70
2.2.6 Displaying the Source Code ................................................................................ 74
2.3 Creating Output ..................................................................................................................... 76
2.3.1 Showing the Standard Dialog Window .......................................................... 76
2.3.2 Writing to the Console ......................................................................................... 78
2.3.3 Using Existing UI Components .......................................................................... 81
2.4 Summary ................................................................................................................................... 83

7
Contents Contents

3 Language Core 85 3.5.8 Modifying Strings via Functions ........................................................................ 188


3.5.9 Functions in Detail ................................................................................................. 189
3.5.10 Calling Functions through User Interaction .................................................. 197
3.1 Storing Values in Variables ............................................................................................... 85
3.1.1 Defining Variables .................................................................................................. 85 3.6 Responding to Errors and Handling Them Correctly ............................................. 198
3.1.2 Using Valid Variable Names ............................................................................... 88 3.6.1 Syntax Errors ............................................................................................................ 198
3.1.3 Defining Constants ................................................................................................ 94 3.6.2 Runtime Errors ......................................................................................................... 199
3.6.3 Logic Errors ............................................................................................................... 200
3.2 Using the Different Data Types ....................................................................................... 94
3.6.4 The Principle of Error Handling .......................................................................... 201
3.2.1 Numbers .................................................................................................................... 95
3.6.5 Catching and Handling Errors ............................................................................ 202
3.2.2 Strings ........................................................................................................................ 98
3.6.6 Triggering Errors ..................................................................................................... 205
3.2.3 Boolean Values ........................................................................................................ 103
3.6.7 Errors and the Function Call Stack .................................................................... 208
3.2.4 Arrays .......................................................................................................................... 104
3.6.8 Calling Certain Statements Regardless of Errors That
3.2.5 Objects ....................................................................................................................... 109
Have Occurred ......................................................................................................... 210
3.2.6 Special Data Types ................................................................................................. 110
3.2.7 Symbols ...................................................................................................................... 112 3.7 Commenting the Source Code ......................................................................................... 216

3.3 Deploying the Different Operators ............................................................................... 112 3.8 Debugging the Code ............................................................................................................. 216
3.3.1 Operators for Working with Numbers ............................................................ 114 3.8.1 Introduction ............................................................................................................. 217
3.3.2 Operators for Easier Assignment ...................................................................... 115 3.8.2 A Simple Code Example ........................................................................................ 217
3.3.3 Operators for Working with Strings ................................................................. 116 3.8.3 Defining Breakpoints ............................................................................................ 218
3.3.4 Operators for Working with Boolean Values ................................................ 117 3.8.4 Viewing Variable Assignments .......................................................................... 220
3.3.5 Operators for Working with Bits ....................................................................... 124 3.8.5 Running a Program Step by Step ....................................................................... 221
3.3.6 Operators for Comparing Values ...................................................................... 125 3.8.6 Defining Multiple Breakpoints ........................................................................... 223
3.3.7 The Optional Chaining Operator ....................................................................... 128 3.8.7 Other Types of Breakpoints ................................................................................. 223
3.3.8 The Logical Assignment Operators ................................................................... 130 3.8.8 Viewing the Function Call Stack ........................................................................ 224
3.3.9 Operators for Special Operations ...................................................................... 132 3.9 Summary ................................................................................................................................... 226
3.4 Controlling the Flow of a Program ................................................................................ 132
3.4.1 Defining Conditional Statements ..................................................................... 133
3.4.2 Defining Branches .................................................................................................. 134
4 Working with Reference Types 229
3.4.3 Using the Selection Operator ............................................................................. 140
3.4.4 Defining Multiway Branches .............................................................................. 142
3.4.5 Defining Counting Loops ..................................................................................... 148
4.1 Difference between Primitive Data Types and Reference Types ..................... 229

3.4.6 Defining Head-Controlled Loops ....................................................................... 155 4.1.1 The Principle of Primitive Data Types .............................................................. 229
3.4.7 Defining Tail-Controlled Loops .......................................................................... 158 4.1.2 The Principle of Reference Types ....................................................................... 230
3.4.8 Prematurely Terminating Loops and Loop Iterations ................................. 160 4.1.3 Primitive Data Types and Reference Types as Function Arguments ..... 232
4.1.4 Determining the Type of a Variable ................................................................. 233
3.5 Creating Reusable Code Blocks ....................................................................................... 168
4.1.5 Outlook ...................................................................................................................... 236
3.5.1 Defining Functions ................................................................................................. 168
3.5.2 Calling Functions .................................................................................................... 171
4.2 Encapsulating State and Behavior in Objects ........................................................... 236

3.5.3 Passing and Evaluating Function Parameters .............................................. 172 4.2.1 Introduction to Object-Oriented Programming ........................................... 236
3.5.4 Defining Return Values ........................................................................................ 180 4.2.2 Creating Objects Using Literal Notation ......................................................... 237
3.5.5 Defining Default Values for Parameters ........................................................ 182 4.2.3 Creating Objects via Constructor Functions ................................................. 239
3.5.6 Using Elements from an Array as Parameters .............................................. 184 4.2.4 Creating Objects Using Classes ......................................................................... 242
3.5.7 Defining Functions Using Short Notation ...................................................... 185 4.2.5 Creating Objects via the [Link]() Function ...................................... 246

8 9
Contents Contents

4.2.6 Accessing Properties and Calling Methods .................................................... 249 4.8 Other Global Objects ............................................................................................................ 325
4.2.7 Adding or Overwriting Object Properties and Object Methods .............. 256 4.8.1 Working with Date and Time Information .................................................... 325
4.2.8 Deleting Object Properties and Object Methods ......................................... 260 4.8.2 Performing Complex Calculations .................................................................... 328
4.2.9 Outputting Object Properties and Object Methods ................................... 262 4.8.3 Wrapper Objects for Primitive Data Types .................................................... 329
4.2.10 Using Symbols to Define Unique Object Properties ................................... 265
4.9 Working with Regular Expressions ............................................................................... 329
4.2.11 Preventing Changes to Objects ......................................................................... 267
4.9.1 Defining Regular Expressions ............................................................................. 330
4.3 Working with Arrays ............................................................................................................ 270 4.9.2 Testing Characters against a Regular Expression ........................................ 330
4.3.1 Creating and Initializing Arrays ......................................................................... 270 4.9.3 Using Character Classes ....................................................................................... 333
4.3.2 Accessing Elements of an Array ......................................................................... 273 4.9.4 Limiting Beginning and End ................................................................................ 336
4.3.3 Adding Elements to an Array .............................................................................. 274 4.9.5 Using Quantifiers ................................................................................................... 339
4.3.4 Removing Elements from an Array .................................................................. 279 4.9.6 Searching for Occurrences .................................................................................. 343
4.3.5 Copying Some of the Elements from an Array ............................................. 282 4.9.7 Searching All Occurrences within a String ..................................................... 344
4.3.6 Sorting Arrays .......................................................................................................... 284 4.9.8 Accessing Individual Parts of an Occurrence ................................................ 345
4.3.7 Using Arrays as a Stack ......................................................................................... 287 4.9.9 Searching for Specific Strings ............................................................................. 346
4.3.8 Using Arrays as a Queue ...................................................................................... 288 4.9.10 Replacing Occurrences within a String ........................................................... 347
4.3.9 Finding Elements in Arrays .................................................................................. 290 4.9.11 Searching for Occurrences .................................................................................. 347
4.3.10 Copying Elements within an Array ................................................................... 292 4.9.12 Splitting Strings ...................................................................................................... 348
4.3.11 Converting Arrays to Strings ............................................................................... 293
4.10 Functions as Reference Types .......................................................................................... 349
4.4 Extracting Values from Arrays and Objects ............................................................... 294 4.10.1 Using Functions as Arguments .......................................................................... 349
4.4.1 Extracting Values from Arrays ........................................................................... 294 4.10.2 Using Functions as Return Values .................................................................... 351
4.4.2 Extracting Values from Objects ......................................................................... 298 4.10.3 Standard Methods of Each Function ............................................................... 353
4.4.3 Extracting Values within a Loop ........................................................................ 302
4.11 Summary ................................................................................................................................... 356
4.4.4 Extracting Arguments of a Function ................................................................ 303
4.4.5 Copying Object Properties to Another Object .............................................. 304
4.4.6 Copying Object Properties from Another Object ......................................... 305
4.5 Working with Strings ........................................................................................................... 306 5 Dynamically Changing Web Pages 357

4.5.1 The Structure of a String ...................................................................................... 306


4.5.2 Determining the Length of a String ................................................................. 307 5.1 Structure of a Web Page ..................................................................................................... 357
4.5.3 Searching within a String .................................................................................... 308 5.1.1 Document Object Model ...................................................................................... 357
4.5.4 Extracting Parts of a String ................................................................................. 310 5.1.2 The Different Types of Nodes ............................................................................. 358
5.1.3 The Document Node ............................................................................................. 361
4.6 Using Maps ............................................................................................................................... 314
4.6.1 Creating Maps ......................................................................................................... 314 5.2 Selecting Elements ................................................................................................................ 363
4.6.2 Basic Operations ..................................................................................................... 315 5.2.1 Selecting Elements by ID ...................................................................................... 364
4.6.3 Iterating over Maps ............................................................................................... 317 5.2.2 Selecting Elements by Class ................................................................................ 367
4.6.4 Using Weak Maps ................................................................................................... 319 5.2.3 Selecting Elements by Element Name ............................................................ 370
5.2.4 Selecting Elements by Name .............................................................................. 371
4.7 Using Sets .................................................................................................................................. 321
5.2.5 Selecting Elements by Selector .......................................................................... 373
4.7.1 Creating Sets ............................................................................................................ 321
5.2.6 Selecting the Parent Element of an Element ................................................ 378
4.7.2 Basic Operations of Sets ....................................................................................... 321
5.2.7 Selecting the Child Elements of an Element ................................................. 381
4.7.3 Iterating over Sets .................................................................................................. 323
5.2.8 Selecting the Sibling Elements of an Element .............................................. 385
4.7.4 Using Weak Sets ..................................................................................................... 324
5.2.9 Calling Selection Methods on Elements ......................................................... 387

10 11
Contents Contents

5.2.10 Selecting Elements by Type ................................................................................ 389 6.4 Understanding and Influencing the Flow of Events .............................................. 439
5.3 Working with Text Nodes .................................................................................................. 390 6.4.1 The Event Phases .................................................................................................... 439
5.3.1 Accessing the Text Content of an Element .................................................... 391 6.4.2 Interrupting the Event Flow ................................................................................ 447
5.3.2 Modifying the Text Content of an Element ................................................... 391 6.4.3 Preventing Default Actions of Events .............................................................. 452
5.3.3 Modifying the HTML below an Element ......................................................... 392 6.5 Programmatically Triggering Events ............................................................................ 454
5.3.4 Creating and Adding Text Nodes ...................................................................... 393 6.5.1 Triggering Simple Events ..................................................................................... 454
5.4 Working with Elements ...................................................................................................... 394 6.5.2 Triggering Events with Passed Arguments .................................................... 455
5.4.1 Creating and Adding Elements .......................................................................... 394 6.5.3 Triggering Default Events .................................................................................... 456
5.4.2 Removing Elements and Nodes ......................................................................... 397 6.6 Summary ................................................................................................................................... 456
5.4.3 The Different Types of HTML Elements .......................................................... 398
5.5 Working with Attributes .................................................................................................... 403
5.5.1 Reading the Value of an Attribute .................................................................... 403 7 Working with Forms 459
5.5.2 Changing the Value of an Attribute or Adding a New Attribute ............ 405
5.5.3 Creating and Adding Attribute Nodes ............................................................. 406
7.1 Accessing Forms and Form Fields ................................................................................... 459
5.5.4 Removing Attributes ............................................................................................. 406
7.1.1 Accessing Forms ...................................................................................................... 459
5.5.5 Accessing CSS classes ............................................................................................ 406
7.1.2 Accessing Form Elements .................................................................................... 463
5.6 Summary ................................................................................................................................... 408 7.1.3 Reading the Value of Text Fields and Password Fields .............................. 465
7.1.4 Reading the Value of Checkboxes ..................................................................... 467
7.1.5 Reading the Value of Radio Buttons ................................................................ 467
7.1.6 Reading the Value of Selection Lists ................................................................ 469
6 Processing and Triggering Events 409
7.1.7 Reading the Values of Multiple Selection Lists ............................................ 470
7.1.8 Populating Selection Lists with Values Using JavaScript .......................... 471
6.1 The Concept of Event-Driven Programming ............................................................. 409
7.2 Programmatically Submitting and Resetting Forms ............................................. 472
6.2 Responding to Events .......................................................................................................... 410
6.2.1 Defining an Event Handler via HTML ............................................................... 412 7.3 Validating Form Inputs ....................................................................................................... 475
6.2.2 Defining an Event Handler via JavaScript ...................................................... 415 7.4 Summary ................................................................................................................................... 485
6.2.3 Defining Event Listeners ...................................................................................... 417
6.2.4 Defining Multiple Event Listeners .................................................................... 418
6.2.5 Passing Arguments to Event Listeners ............................................................ 420
6.2.6 Removing Event Listeners .................................................................................... 422
8 Controlling Browsers and Reading Browser
6.2.7 Defining Event Handlers and Event Listeners via a Helper Function .... 423 Information 487
6.2.8 Accessing Information of an Event ................................................................... 424
6.3 The Different Types of Events .......................................................................................... 426 8.1 The Browser Object Model ................................................................................................ 487
6.3.1 Events when Interacting with the Mouse ...................................................... 427 8.2 Accessing Window Information ...................................................................................... 489
6.3.2 Events when Interacting with the Keyboard and with Text Fields ........ 431 8.2.1 Determining the Size and Position of a Browser Window ....................... 489
6.3.3 Events when Working with Forms ................................................................... 434 8.2.2 Changing the Size and Position of a Browser Window ............................. 490
6.3.4 Events when Focusing Elements ....................................................................... 435 8.2.3 Accessing Display Information of the Browser Bars ................................... 492
6.3.5 General Events of the User Interface ............................................................... 435 8.2.4 Determining General Properties ....................................................................... 493
6.3.6 Events on Mobile Devices .................................................................................... 438 8.2.5 Opening New Browser Windows ...................................................................... 494
8.2.6 Closing the Browser Window ............................................................................. 495

12 13
Contents Contents

8.2.7 Opening Dialogs ..................................................................................................... 496 9.4.4 Loading JSON Data via Ajax ................................................................................ 543
8.2.8 Executing Functions in a Time-Controlled Manner .................................... 497 9.4.5 Sending Data to the Server via Ajax ................................................................. 545
8.3 Accessing Navigation Information of a Currently Open Web Page ................ 499 9.4.6 Submitting Dorms via Ajax ................................................................................. 546
9.4.7 Loading Data from Other Domains .................................................................. 547
8.3.1 Accessing the Individual Components of the URL ....................................... 499
9.4.8 The Newer Alternative to XMLHttpRequest: The Fetch API ..................... 550
8.3.2 Accessing Query String Parameters ................................................................. 500
8.3.3 Loading a New Web Page .................................................................................... 500 9.5 Summary ................................................................................................................................... 554

8.4 Viewing and Modifying the Browsing History ......................................................... 502


8.4.1 Navigating in the Browsing History ................................................................. 502
8.4.2 Browsing History for Single-Page Applications ............................................ 503 10 Simplifying Tasks with jQuery 555
8.4.3 Adding Entries to the Browsing History ......................................................... 503
8.4.4 Responding to Changes in the Browsing History ........................................ 506
10.1 Introduction ............................................................................................................................. 555
8.4.5 Replacing the Current Entry in the Browsing History ................................ 506
10.1.1 Embedding jQuery ................................................................................................. 556
8.5 Recognizing Browsers and Determining Browser Features ............................... 508 10.1.2 Embedding jQuery via a Content Delivery Network ................................... 557
8.6 Accessing Screen Information .......................................................................................... 510 10.1.3 Using jQuery ............................................................................................................. 558
10.1.4 Simplifying Tasks with jQuery ........................................................................... 559
8.7 Summary ................................................................................................................................... 511
10.2 Working with the DOM ...................................................................................................... 560
10.2.1 Selecting Elements ................................................................................................. 561
10.2.2 Accessing and Modifying Content .................................................................... 566
9 Dynamically Reloading Contents of a Web Page 513 10.2.3 Filtering Selected Elements ................................................................................. 569
10.2.4 Accessing Attributes .............................................................................................. 571
9.1 The Principle of Ajax ............................................................................................................ 513 10.2.5 Accessing CSS Properties ..................................................................................... 572
9.1.1 Synchronous Communication ........................................................................... 513 10.2.6 Navigating between Elements .......................................................................... 573
9.1.2 Asynchronous Communication ......................................................................... 514 10.2.7 Using Effects and Animations ............................................................................ 575
9.1.3 Typical Use Cases for Ajax ................................................................................... 516 10.3 Responding to Events .......................................................................................................... 576
9.1.4 Data Formats Used ................................................................................................ 518 10.3.1 Registering Event Listeners ................................................................................. 577
9.2 The XML Format ..................................................................................................................... 519 10.3.2 Responding to General Events ........................................................................... 578
9.2.1 The Structure of XML ............................................................................................ 519 10.3.3 Responding to Mouse Events ............................................................................. 579
9.2.2 XML and the DOM API .......................................................................................... 521 10.3.4 Responding to Keyboard Events ........................................................................ 581
9.2.3 Converting Strings to XML Objects .................................................................. 522 10.3.5 Responding to Form Events ................................................................................ 581
9.2.4 Converting XML Objects to Strings .................................................................. 523 10.3.6 Accessing Information from Events ................................................................. 582

9.3 The JSON Format .................................................................................................................... 524 10.4 Creating Ajax Requests ....................................................................................................... 584
9.3.1 The Structure of JSON ........................................................................................... 524 10.4.1 Creating Ajax Requests ........................................................................................ 584
9.3.2 Difference between JSON and JavaScript Objects ...................................... 526 10.4.2 Responding to Events ............................................................................................ 587
9.3.3 Converting Objects to JSON Format ................................................................ 527 10.4.3 Loading HTML Data via Ajax ............................................................................... 588
9.3.4 Converting Objects from JSON Format ........................................................... 528 10.4.4 Loading XML Data via Ajax .................................................................................. 589
10.4.5 Loading JSON Data via Ajax ................................................................................ 590
9.4 Making Requests via Ajax ................................................................................................. 529
9.4.1 The XMLHttpRequest Object .............................................................................. 529 10.5 Summary ................................................................................................................................... 592
9.4.2 Loading HTML Data via Ajax ............................................................................... 535
9.4.3 Loading XML Data via Ajax .................................................................................. 539

14 15
Contents Contents

11 Dynamically Creating Images and Graphics 599 12.4 Using the Browser Database ............................................................................................ 654
12.4.1 Opening a Database .............................................................................................. 655
12.4.2 Creating a Database .............................................................................................. 656
11.1 Drawing Images ..................................................................................................................... 599
12.4.3 Creating an Object Store ...................................................................................... 657
11.1.1 The Drawing Area ................................................................................................... 599
12.4.4 Adding Objects to an Object Store ................................................................... 657
11.1.2 The Rendering Context ......................................................................................... 600
12.4.5 Reading Objects from an Object Store ............................................................ 661
11.1.3 Drawing Rectangles ............................................................................................... 602
12.4.6 Deleting Objects from an Object Store ........................................................... 661
11.1.4 Using Paths ............................................................................................................... 604
12.4.7 Updating Objects in an Object Store ............................................................... 663
11.1.5 Drawing Texts ......................................................................................................... 610
12.4.8 Using a Cursor ......................................................................................................... 664
11.1.6 Drawing Gradients ................................................................................................. 611
11.1.7 Saving and Restoring the Canvas State .......................................................... 613 12.5 Accessing the File System .................................................................................................. 665
11.1.8 Using Transformations ......................................................................................... 615 12.5.1 Selecting Files via File Dialog .............................................................................. 666
11.1.9 Creating Animations ............................................................................................. 618 12.5.2 Selecting Files via Drag and Drop ...................................................................... 667
12.5.3 Reading Files ............................................................................................................ 668
11.2 Integrating Vector Graphics ............................................................................................. 620
12.5.4 Monitoring the Reading Progress ..................................................................... 671
11.2.1 The SVG Format ...................................................................................................... 620
11.2.2 Integrating SVG in HTML ..................................................................................... 621 12.6 Moving Components of a Web Page ............................................................................ 673
11.2.3 Changing the Appearance of SVG Elements with CSS .............................. 624 12.6.1 Events of a Drag-and-Drop Operation ............................................................ 673
11.2.4 Manipulating the Behavior of SVG Elements via JavaScript .................... 625 12.6.2 Defining Movable Elements ............................................................................... 674
12.6.3 Moving Elements .................................................................................................... 676
11.3 Summary ................................................................................................................................... 627
12.7 Parallelizing Tasks ................................................................................................................. 678
12.7.1 The Principle of Web Workers ............................................................................ 679
12.7.2 Use Web Workers ................................................................................................... 680
12 Using Modern Web APIs 629
12.8 Determining the Location of Users ................................................................................ 682
12.8.1 Accessing Location Information ........................................................................ 682
12.1 Communicating via JavaScript ........................................................................................ 631
12.8.2 Continuously Accessing Location Information ............................................. 684
12.1.1 Unidirectional Communication with the Server .......................................... 631
12.8.3 Showing the Position on a Map ......................................................................... 685
12.1.2 Bidirectional Communication with a Server ................................................. 633
12.8.4 Showing Directions ................................................................................................ 686
12.1.3 Outgoing Communication from the Server .................................................. 635
12.9 Reading the Battery Level of an End Device .............................................................. 688
12.2 Recognizing Users ................................................................................................................. 639
12.9.1 Accessing Battery Information .......................................................................... 688
12.2.1 Using Cookies .......................................................................................................... 639
12.9.2 Responding to Events ............................................................................................ 689
12.2.2 Creating Cookies ..................................................................................................... 641
12.2.3 Reading Cookies ...................................................................................................... 642 12.10 Outputting Speech and Recognizing Speech ............................................................ 691
12.2.4 Example: Shopping Cart Based on Cookies ................................................... 644 12.10.1 Outputting Speech ................................................................................................. 692
12.2.5 Disadvantages of Cookies .................................................................................... 647 12.10.2 Recognizing Speech ............................................................................................... 694

12.3 Using the Browser Storage ................................................................................................ 647 12.11 Creating Animations ............................................................................................................ 695
12.3.1 Storing Values in the Browser Storage ........................................................... 648 12.11.1 Using the API ............................................................................................................ 696
12.3.2 Reading Values from the Browser Storage .................................................... 649 12.11.2 Controlling an Animation .................................................................................... 699
12.3.3 Updating Values in the Browser Storage ....................................................... 649 12.12 Working with the Command Line .................................................................................. 699
12.3.4 Deleting Values from the Browser Storage ................................................... 650 12.12.1 Selecting and Inspecting DOM Elements ....................................................... 701
12.3.5 Responding to Changes in the Browser Storage .......................................... 650 12.12.2 Events Analysis ........................................................................................................ 704
12.3.6 The Different Types of Browser Storage ......................................................... 651 12.12.3 Debugging, Monitoring, and Profiling ............................................................ 704
12.3.7 Example: Shopping Cart Based on the Browser Storage .......................... 653

16 17
Contents Contents

12.13 Developing Multilingual Applications ......................................................................... 708 13.4 Object Orientation with Class Syntax .......................................................................... 745
12.13.1 Explanation of Terms ............................................................................................ 709 13.4.1 Defining Classes ...................................................................................................... 746
12.13.2 The Internationalization API ............................................................................... 710 13.4.2 Creating Object Instances ................................................................................... 748
12.13.3 Comparing Character String Expressions ...................................................... 712 13.4.3 Defining Getters and Setters .............................................................................. 748
12.13.4 Formatting Dates and Times .............................................................................. 714 13.4.4 Defining Private Properties and Private Methods ....................................... 750
12.13.5 Formatting Numeric Values ............................................................................... 717 13.4.5 Deriving from "Classes" ........................................................................................ 753
12.14 Overview of Various Web APIs ........................................................................................ 720 13.4.6 Overwriting Methods ............................................................................................ 757
13.4.7 Calling Methods of the "Superclass" ................................................................ 759
12.15 Summary ................................................................................................................................... 724
13.4.8 Defining Static Methods ...................................................................................... 760
13.4.9 Defining Static Properties .................................................................................... 762
13.4.10 Class Syntax and the Principles of Object Orientation .............................. 763
13 Object-Oriented Programming 725 13.5 Summary ................................................................................................................................... 764

13.1 The Principles of Object-Oriented Programming .................................................... 725


13.1.1 Classes, Object Instances, and Prototypes ..................................................... 726
14 Functional Programming 765
13.1.2 Principle 1: Define Abstract Behavior .............................................................. 728
13.1.3 Principle 2: Encapsulate Condition and Behavior ........................................ 728
14.1 Principles of Functional Programming ........................................................................ 765
13.1.4 Principle 3: Inherit Condition and Behavior .................................................. 729
13.1.5 Principle 4: Accept Different Types .................................................................. 731 14.2 Imperative Programming and Functional Programming .................................... 767
13.1.6 JavaScript and Object Orientation .................................................................... 731 14.2.1 Iterating with the forEach() Method ................................................................ 767
13.2 Prototypical Object Orientation ..................................................................................... 732 14.2.2 Mapping Values with the map() Method ....................................................... 770
14.2.3 Filtering Values with the filter() Method ....................................................... 771
13.2.1 The Concept of Prototypes .................................................................................. 732
14.2.4 Reducing Multiple Values to One Value with the reduce() Method ..... 773
13.2.2 Deriving from Objects ........................................................................................... 733
14.2.5 Combination of the Different Methods .......................................................... 775
13.2.3 Inheriting Methods and Properties .................................................................. 733
13.2.4 Defining Methods and Properties in the Inheriting Object ..................... 734 14.3 Summary ................................................................................................................................... 776
13.2.5 Overwriting Methods ............................................................................................ 735
13.2.6 The Prototype Chain .............................................................................................. 736
13.2.7 Calling Methods of the Prototype ..................................................................... 737
13.2.8 Prototypical Object Orientation and the Principles of
15 Correctly Structuring the Source Code 779

Object Orientation ................................................................................................. 738


15.1 Avoiding Name Conflicts .................................................................................................... 779
13.3 Pseudoclassical Object Orientation ............................................................................... 739
13.3.1 Defining Constructor Functions ........................................................................ 739 15.2 Defining and Using Modules ............................................................................................ 783
13.3.2 Creating Object Instances ................................................................................... 739 15.2.1 The Module Design Pattern ................................................................................ 783
13.3.3 Defining Methods .................................................................................................. 740 15.2.2 The Revealing Module Design Pattern ............................................................ 786
13.3.4 Deriving from Objects ........................................................................................... 740 15.2.3 AMD ............................................................................................................................ 791
13.3.5 Calling the Constructor of the "Superclass" .................................................. 744 15.2.4 CommonJS ................................................................................................................ 792
13.3.6 Overwriting Methods ............................................................................................ 744 15.2.5 Native Modules ....................................................................................................... 794
13.3.7 Calling Methods of the "Superclass" ................................................................ 745 15.3 Summary ................................................................................................................................... 797
13.3.8 Pseudoclassical Object Orientation and the Principles of
Object Orientation ................................................................................................. 745

18 19
Contents Contents

16 Using Asynchronous Programming and 17.3.3 Intercepting an Event Exactly Once ................................................................. 844
17.3.4 Intercepting an Event Multiple Times ............................................................. 845
Other Advanced Features 799
17.4 Accessing the File System .................................................................................................. 846

16.1 Understanding and Using Asynchronous Programming ..................................... 799 17.4.1 Reading Files ............................................................................................................ 846
17.4.2 Writing Files ............................................................................................................. 847
16.1.1 Using the Callback Design Pattern ................................................................... 800
17.4.3 Reading File Information ..................................................................................... 848
16.1.2 Using Promises ........................................................................................................ 804
17.4.4 Deleting Files ........................................................................................................... 849
16.1.3 Using Async Functions .......................................................................................... 813
17.4.5 Working with Directories ..................................................................................... 849
16.2 Encapsulating Iteration over Data Structures .......................................................... 816
17.5 Creating a Web Server ......................................................................................................... 851
16.2.1 The Principle of Iterators ...................................................................................... 816
17.5.1 Starting a Web Server ........................................................................................... 851
16.2.2 Using Iterators ......................................................................................................... 817
17.5.2 Making Files Available via Web Server ............................................................ 852
16.2.3 Creating Your Own Iterator ................................................................................ 817
17.5.3 Creating a Client for a Web Server ................................................................... 853
16.2.4 Creating an Iterable Object ................................................................................. 819
17.5.4 Defining Routes ...................................................................................................... 853
16.2.5 Iterating over Iterable Objects ........................................................................... 820
17.5.5 Using the [Link] Web Framework ............................................................. 854
16.3 Pausing and Resuming Functions .................................................................................. 820
17.6 Accessing Databases ............................................................................................................ 859
16.3.1 Creating a Generator Function .......................................................................... 821
17.6.1 MongoDB Installation ........................................................................................... 859
16.3.2 Creating a Generator ............................................................................................. 821
17.6.2 Installing a MongoDB Driver for [Link] ........................................................ 860
16.3.3 Iterating over Generators .................................................................................... 822
17.6.3 Establishing a Connection to the Database .................................................. 860
16.3.4 Creating Infinite Generators ............................................................................... 822
17.6.4 Creating a Collection ............................................................................................. 861
16.3.5 Controlling Generators with Parameters ....................................................... 823
17.6.5 Saving Objects ......................................................................................................... 862
16.4 Intercepting Access to Objects ........................................................................................ 824 17.6.6 Reading Objects ...................................................................................................... 862
16.4.1 The Principle of Proxies ........................................................................................ 824 17.6.7 Updating Objects .................................................................................................... 865
16.4.2 Creating Proxies ...................................................................................................... 825 17.6.8 Deleting Objects ..................................................................................................... 865
16.4.3 Defining Handlers for Proxies ............................................................................ 825
17.7 Working with Streams ........................................................................................................ 866
16.5 Summary ................................................................................................................................... 829 17.7.1 Introduction and Types of Streams .................................................................. 866
17.7.2 Stream Use Cases ................................................................................................... 867
17.7.3 Reading Data with Streams ................................................................................ 868
17 Creating Server-Based Applications with [Link] 831 17.7.4 Writing Data with Streams ................................................................................. 869
17.7.5 Combining Streams Using Piping ..................................................................... 870
17.7.6 Error Handling during Piping .............................................................................. 873
17.1 Introduction to [Link] ....................................................................................................... 831
17.1.1 The Architecture of [Link] ................................................................................ 831 17.8 Summary ................................................................................................................................... 874
17.1.2 Installing [Link] .................................................................................................... 833
17.1.3 A Simple Application ............................................................................................. 833
17.2 Managing [Link] Packages ............................................................................................. 834 18 Creating Mobile Applications with JavaScript 877
17.2.1 Installing the [Link] Package Manager ........................................................ 834
17.2.2 Installing Packages ................................................................................................. 835 18.1 The Different Types of Mobile Applications .............................................................. 877
17.2.3 Creating Your Own Packages ............................................................................. 838 18.1.1 Native Applications ................................................................................................ 877
17.3 Processing and Triggering Events .................................................................................. 841 18.1.2 Mobile Web Applications ..................................................................................... 878
17.3.1 Triggering and Intercepting an Event .............................................................. 841 18.1.3 Hybrid Applications ............................................................................................... 879
17.3.2 Triggering an Event Multiple Times ................................................................. 844 18.1.4 Comparison of the Different Approaches ...................................................... 881

20 21
Contents Contents

18.2 Creating Mobile Applications with React Native .................................................... 883 20.2.3 Controlling LEDs ...................................................................................................... 917
18.2.1 The Principle of React Native .............................................................................. 883 20.2.4 Programming the Push Buttons ........................................................................ 919
18.2.2 Installation and Project Initialization .............................................................. 883 20.2.5 Extending the Tessel with Modules ................................................................. 920
18.2.3 Starting the Application ....................................................................................... 884 20.3 BeagleBone Black .................................................................................................................. 921
18.2.4 The Basic Structure of a React Native Application ...................................... 887 20.3.1 Technical Information .......................................................................................... 921
18.2.5 Using UI Components ........................................................................................... 889 20.3.2 Connection and Installation ............................................................................... 922
18.2.6 Communication with the Server ....................................................................... 894 20.3.3 Controlling LEDs ...................................................................................................... 923
18.2.7 Building and Publishing Applications .............................................................. 895
20.4 Arduino ....................................................................................................................................... 924
18.3 Summary ................................................................................................................................... 895 20.4.1 The Firmata Protocol ............................................................................................. 924
20.4.2 Connection and Installation ............................................................................... 925
20.4.3 The Johnny Five [Link] Module ....................................................................... 925
19 Desktop Applications with JavaScript 897 20.5 [Link] ....................................................................................................................................... 927
20.5.1 Controlling the BeagleBone Black with [Link] .......................................... 927
19.1 [Link] ........................................................................................................................................... 898 20.5.2 Controlling the Tessel Board with [Link] .................................................... 928
19.1.1 Installing and Creating an Application ........................................................... 899 20.5.3 Controlling an Arduino with [Link] .............................................................. 928
19.1.2 Starting the Application ....................................................................................... 900 20.6 Summary ................................................................................................................................... 929
19.1.3 Packaging of the Application .............................................................................. 901
19.1.4 More Sample Applications .................................................................................. 902
19.2 Electron ...................................................................................................................................... 903
21 Establishing a Professional Development Process 931
19.2.1 Installing and Creating an Application ........................................................... 904
19.2.2 Starting the Application ....................................................................................... 906
21.1 Automating Tasks ................................................................................................................. 931
19.2.3 Packaging .................................................................................................................. 906
21.1.1 Automating Tasks with Grunt ........................................................................... 931
19.2.4 More Sample Applications .................................................................................. 907
21.1.2 Automating Tasks with Gulp .............................................................................. 935
19.3 Summary ................................................................................................................................... 908
21.2 Automated Testing of Source Code ............................................................................... 936
21.2.1 The Principle of Automated Tests ..................................................................... 936
21.2.2 The Principle of Test-Driven Development .................................................... 937
20 Controlling Microcontrollers with JavaScript 909 21.2.3 Automated Testing of Source Code with QUnit .......................................... 939
21.2.4 Automated Testing of Source Code with mocha ......................................... 945
20.1 Espruino ..................................................................................................................................... 910 21.3 Source Code Version Management ............................................................................... 949
20.1.1 Technical Information .......................................................................................... 910 21.3.1 Introduction to Version Management ............................................................ 949
20.1.2 Connection and Installation ............................................................................... 911 21.3.2 Installing and Configuring the Git Version Control System .................... 953
20.1.3 First Example ........................................................................................................... 911 21.3.3 Creating a New Local Repository ....................................................................... 954
20.1.4 Controlling LEDs ...................................................................................................... 912 21.3.4 Cloning an Existing Repository .......................................................................... 954
20.1.5 More Modules ......................................................................................................... 914 21.3.5 Transferring Changes to the Staging Area .................................................... 955
20.1.6 Reading Sensors ...................................................................................................... 915 21.3.6 Transferring Changes to the Local Repository .............................................. 956
20.2 Tessel ........................................................................................................................................... 916 21.3.7 The Different States in Git ................................................................................... 957
20.2.1 Technical Information .......................................................................................... 916 21.3.8 Transfering Changes to the Remote Repository .......................................... 958
20.2.2 Connection and Installation ............................................................................... 917 21.3.9 Transferring Changes from the Remote Repository ................................... 959

22 23
Contents

21.3.10 Working in a New Branch .................................................................................... 960


21.3.11 Adopting Changes from a Branch ..................................................................... 961
21.3.12 Overview of the Most Important Commands and Terms ........................ 962
21.4 Summary ................................................................................................................................... 965

The Author ............................................................................................................................................... 967


Index .......................................................................................................................................................... 969

24
Index

__proto__ ...................................................... 241, 732 Array ................................................................. 104, 270


:invalid ...................................................................... 477 access elements ................................................ 273
:required ................................................................... 477 add elements ..................................................... 274
:valid .......................................................................... 477 convert to strings ............................................. 293
<canvas> ................................................................... 599 copy elements .......................................... 282, 292
<noscript> ................................................................... 70 create .................................................................... 270
<script> ........................................................................ 70 elements .............................................................. 104
$() ................................................................................. 558 entries ................................................................... 104
extract elements .............................................. 294
A find elements ..................................................... 290
index-based structure .................................... 106
Abstraction .................................................... 725, 728 initialize ............................................................... 270
Access property .................................. 247, 255, 739 multidimensional ............................................ 106
Accessing attributes ............................................ 571 remove elements .............................................. 279
Accessing CSS properties ................................... 572 sort ........................................................................ 284
Accessor .................................................................... 729 use as queue ...................................................... 288
Accessor method .................................................. 729 use as stack ........................................................ 287
Actuator .................................................................... 909 values ................................................................... 104
addEventListener() ............................................... 417 Array destructuring ............................................. 294
Addition .................................................................... 114 Array literal notation ....................... 104, 270, 271
Aggregation ............................................................. 726 [Link]() ....................................................... 235
Ajax ............................................................ 48, 513, 584 Arrow function ...................................................... 186
alert() ..................................................................... 66, 76 Assembly language ................................................. 33
Algorithm .................................................................... 32 Assertion .................................................................. 936
AMD ........................................................................... 791 Assignment operator ................................... 86, 115
Analyze events ....................................................... 704 Association ............................................................. 726
AND operator ......................................................... 117 Async functions ............................................. 72, 813
Android .............................................................. 51, 877 Asynchronous JavaScript and XML ........ 48, 513
Animation ............................................................... 696 Asynchronous module definition ................. 783
AnimationEffectTiming ................................. 696 Asynchronous programming ......................... 799
AnimationTimeline ......................................... 696 Atom ............................................................................. 60
cancel .................................................................... 699 attachEvent() .......................................................... 418
pause ..................................................................... 699 Attribute .................................................................. 109
start ....................................................................... 699 Attribute node ....................................................... 360
Anonymous function ......................................... 169 Automatic builds ..................................................... 61
Answer ...................................................................... 513
App .............................................................................. 877 B
appendChild() ......................................................... 394
Apple .......................................................................... 877 Backend ....................................................................... 48
Application ................................................................. 32 Bad practices ............................................................. 48
hybrid ....................................................................... 52 Battery Status API ................................................ 688
native ............................................................... 36, 51 BeagleBone Black .................................................. 921
application/ecmascript ......................................... 68 control LEDs ....................................................... 923
application/javascript ............................................ 68 Behavior ................................................................... 726
apply() ........................................................................ 356 Behavioral layer ....................................................... 58
Arduino ..................................................................... 924 Best practices ............................................................ 48
Argument ....................................................... 172, 173 Bidirectional communication ......................... 631

969
Index Index

Binary buffer ........................................................... 868 C Client side ................................................................... 48 Convert string


Binary code ................................................................. 33 Closure ...................................................................... 783 to XML objects .................................................. 522
Binary Large Object .............................................. 634 Cache ............................................................................ 85 Cloud9 IDE ............................................................... 922 Cookie .............................................................. 639, 641
Binary notation ........................................................ 96 call() ............................................................................. 355 CLR ................................................................................. 38 CORS .......................................................................... 549
Binary number .......................................................... 96 Callback ..................................................................... 800 Code, global ............................................................. 191 CouchDB .................................................................. 654
bind() .......................................................................... 353 Callback design pattern ...................................... 800 Collator ..................................................................... 712 Counter variable ................................................... 148
Blob ................................................................... 634, 665 Callback function ........................................ 769, 800 Collection ................................................................. 861 Counting loop ........................................................ 148
Blocking I/O ............................................................ 831 Callback handler .................................................... 800 Column families .................................................... 654 Coupling ................................................................... 726
Boilerplate code ..................................................... 767 Callback hell ............................................................. 803 Command line ....................................................... 699 Create object
BOM API ................................................................... 487 CamelCase spelling ................................................. 92 Command Line API .............................................. 700 classes .................................................................. 242
BoneScript ............................................................... 922 Canvas API ...................................................... 430, 599 Debugging .......................................................... 704 constructor functions .................................... 239
Boolean ..................................................................... 103 2D rendering context ...................................... 600 Monitoring ......................................................... 704 literal notation ................................................. 237
Boolean value ......................................................... 103 3D rendering context ...................................... 600 Profiling ............................................................... 704 [Link]() ................................................... 246
Bootstrap .................................................................. 462 drawing arcs and circles ................................ 608 Comment ................................................................. 216 createAttribute() .......................................... 403, 406
Branch .................................................... 133, 134, 960 drawing area ...................................................... 599 multi-line ............................................................. 216 createElement() ..................................................... 394
break .......................................................................... 160 drawing Bezier curves ..................................... 607 Common Language Runtime .............................. 38 createTextNode() .................................................. 393
Breakpoint ............................................................... 218 drawing rectangles .......................................... 602 CommonJS ..................................................... 783, 792 Creating Ajax requests ....................................... 584
conditional ......................................................... 223 drawing square curves ................................... 607 Communication Cross-origin request ............................................ 547
DOM ...................................................................... 224 drawing texts ..................................................... 610 asynchronous .................................................... 514 proxy ..................................................................... 548
event listener ...................................................... 224 rendering context ............................................. 600 bidirectional ....................................................... 631 Cross-Origin Resource Sharing ....................... 549
XHR ........................................................................ 224 rotation ................................................................ 616 synchronous ....................................................... 513 CRUD ......................................................................... 654
Browser scaling ................................................................... 615 unidirectional .................................................... 631 CSS ................................................................................. 55
address bar ......................................................... 493 translation .......................................................... 617 Comparing character string expressions .... 712 class ....................................................................... 367
menu bar ............................................................. 493 using paths .......................................................... 604 Compiler ...................................................................... 35 CSS3 .............................................................................. 51
personal bar ....................................................... 493 CanvasRenderingContext2D ............................ 601 Component test .................................................... 938 media queries .................................................... 878
recognize ............................................................. 508 Capturing phase ..................................................... 439 Composition ........................................................... 726 Cursor ........................................................................ 664
scrollbars ............................................................. 493 Cascading Style Sheets .......................................... 51 Concatenation ........................................................ 116 CustomEvent ......................................................... 455
status bar ............................................................ 493 catch ........................................................................... 202 configurable ............................................................ 247 CVS ............................................................................. 949
toolbar .................................................................. 493 Character class ........................................................ 333 confirm() ..................................................................... 76 [Link] ..................................................................... 927
Browser database .................................................. 654 negation ............................................................... 333 Confirmation dialog ............................................... 76
Browser detection ................................................ 509 predefined ............................................................ 334 Console ................................................................ 78, 79 D
Browser feature ..................................................... 508 range ...................................................................... 333 show in Chrome ................................................... 78
Browser Object Model ......................................... 487 simple class ......................................................... 333 show in Firefox ..................................................... 78 Data encapsulation .................. 252, 725, 728, 782
Browser sniffing .................................................... 509 Checkbox, read ....................................................... 467 show in Opera ....................................................... 78 Data property ................................................ 255, 739
Browser storage ..................................................... 647 checkValidity() ........................................................ 482 show in Safari ....................................................... 78 Data structure ........................................................ 358
Browser window Chrome DevTools ................................ 78, 217, 361 const .............................................................................. 94 Data type .............................................................. 94, 95
change position ................................................ 490 Class .................................................................. 242, 726 Constant ...................................................................... 94 primitive ................................................................. 94
close ....................................................................... 495 defining ................................................................ 746 define ....................................................................... 94 special .................................................................. 110
determine general properties ...................... 493 deriving ................................................................. 730 Constraint Validation API ................................. 478 Data URL .................................................................. 669
determine position .......................................... 489 that inherits ........................................................ 730 Constructor ............................................................. 748 Data, numeric ........................................................... 95
determine size ................................................... 489 Class body ....................................................... 243, 746 constructor .............................................................. 241 Database ................................................................... 654
open new ............................................................. 494 Class declaration .................................................... 746 Constructor function ....................... 239, 270, 739 create .................................................................... 656
resize ..................................................................... 490 Class diagram ................................................ 236, 726 constructor() ................................................. 243, 747 document-oriented ......................................... 859
Browsing history ................................................... 502 Class expressions .................................................. 747 Content delivery network ................................. 557 transaction ......................................................... 658
replace current entry ...................................... 506 Class that inherits ................................................. 730 Content distribution network ......................... 557 Database schema ......................................... 655, 657
respond to changes ......................................... 506 Class under test ...................................................... 936 Content layer ............................................................. 58 Date ............................................................................ 325
state object ......................................................... 504 Class-based object orientation ......................... 727 Content type .............................................................. 68 DateTimeFormat .................................................. 714
Bubbling phase ...................................................... 439 Class-based programming language ............. 727 Context object ........................................................ 192 Debugging ..................................... 80, 216, 217, 219
Bug .............................................................................. 200 Classless programming ...................................... 727 continue ......................................................... 160, 162 Decision point .......................................................... 43
Build tool .................................................................. 931 classList ..................................................................... 407 Control character .................................................. 100 Declarative .............................................................. 766
Bytecode ...................................................................... 39 className ................................................................ 407 Control structure .................................................. 133 Decrement operator ........................................... 114
Client .......................................................................... 513 Default parameter ................................................ 182

970 971
Index Index

Default value .......................................................... 182 DOM (Cont.) Escaping ....................................................................... 99 Execution context ............................................... 191
Defensive programming ................................... 365 read attributes ................................................... 403 Espruino ............................................................ 52, 910 global .................................................................... 191
defer .............................................................................. 72 remove attributes ............................................. 406 control LEDs ....................................................... 912 Exponential operator ......................................... 114
Define animations ................................................ 695 Scripting ................................................................. 48 HTTP client ......................................................... 914 export ........................................................................ 794
Define movable element ................................... 674 tree .......................................................................... 357 HTTP server ........................................................ 914 Export object .......................................................... 785
Delete ......................................................................... 260 DOMContentLoaded ............................................ 417 read files .............................................................. 914 Extensible Markup Language ................. 518, 519
Deriving class ......................................................... 730 DOMParser ............................................................... 522 read sensors ........................................................ 915 Extension sub tags ............................................... 710
Design pattern ....................................................... 783 Dot notation ............................................................ 249 Web IDE ................................................................ 911
Desktop applications ........................................... 897 Drag and Drop API ...................................... 667, 673 write files ............................................................. 914 F
Destructuring ......................................................... 294 Drag source .............................................................. 673 European Computer Manufacturers
Destructuring statement ................................... 294 Drag-and-drop operation ................................... 673 Asssociation .......................................................... 46 False ........................................................................... 103
Determine events .................................................................... 673 eval() ........................................................................... 191 Falsy ........................................................................... 119
date ........................................................................ 326 Drawing a Bézier curve ....................................... 607 EvalError ................................................................... 203 Fat arrow function ............................................... 186
day of month ..................................................... 326 Drawing arcs and circles ..................................... 608 Event .......................................................................... 409 Feature detection ........................................ 509, 602
hour ....................................................................... 326 Drawing area ........................................................... 599 access information of the event ................. 424 Fetch API ......................................................... 550, 894
minute .................................................................. 326 Drawing text ........................................................... 610 bind ........................................................................ 410 File .............................................................................. 665
month ................................................................... 326 Drop target ............................................................... 673 bubbling ..................................................... 440, 441 delete .................................................................... 849
seconds ................................................................. 326 DTD ............................................................................. 519 capturing ................................................... 440, 445 read ....................................................................... 846
the current month ........................................... 325 Duplex streams ...................................................... 867 emitter ........................................................ 409, 841 write ...................................................................... 847
time ........................................................................ 326 Dynamic HTML ........................................................ 48 focus events ........................................................ 435 FileList ....................................................................... 665
weekday ............................................................... 326 form events ......................................................... 434 FileReader ....................................................... 665, 668
year ........................................................................ 326 E intercept ............................................................... 841 filter() ......................................................................... 771
Development environment ................................ 61 keyboard events ................................................ 431 finally ........................................................................ 210
Development, test-driven ................................. 937 Easing function ...................................................... 575 loop .............................................................. 409, 832 find() ................................................................. 292, 775
Directory ECMAScript ................................................................ 46 method ................................................................. 577 findIndex() .............................................................. 292
create .................................................................... 849 Editor ............................................................................ 59 mobile devices ................................................... 438 Firebug ......................................................................... 79
delete ..................................................................... 849 Eich, Brendan ............................................................ 46 mouse events ..................................................... 427 Firmata protocol ................................................... 924
list files .................................................................. 849 Electron ..................................................................... 903 phase ..................................................................... 439 First in, first out .................................................... 288
dispatchEvent() ...................................................... 454 installation .......................................................... 904 prevent default actions .................................. 452 firstChild .................................................................. 383
Diversity ................................................................... 731 packaging ............................................................ 906 queue ..................................................................... 409 First-class citizen .................................................. 765
Division ..................................................................... 114 Element respond to events ............................................. 410 First-class object ................................................... 765
Document ................................................................ 359 filter ........................................................................ 569 trigger ................................................ 409, 454, 841 firstElementChild ................................................. 383
Document database ............................................. 654 getAttribute() ..................................................... 403 trigger programmatically ............................ 454 Flag ............................................................................. 344
Document node .......................................... 359, 361 move ...................................................................... 676 user interface events ....................................... 435 Flowchart .................................................................... 41
Document Object Model ................................... 357 navigate between ............................................. 573 Event flow ................................................................ 439 Flowchart notation ................................................. 41
Document type definition ................................ 519 node ....................................................................... 359 interrupt .............................................................. 447 Fluent API ................................................................ 581
[Link] ............................................... 390 removeAttribute() ............................................. 403 Event handler .................................................. 73, 409 Focus event ............................................................. 435
[Link] ..................................................... 390 select ............................................................ 363, 561 define via HTML ............................................... 412 FocusEvent .............................................................. 435
[Link] ................................................... 390 select by class ..................................................... 367 define via JavaScript ....................................... 415 for loop ..................................................................... 149
[Link] ..................................................... 390 select by element name .................................. 370 helper function .................................................. 423 forEach() .......................................................... 351, 767
[Link] ................................................. 390 select by ID .......................................................... 364 Event listener ............................................................ 73 for-in loop ............................................ 247, 262, 317
[Link] ...................................................... 390 select by name ................................................... 371 define .................................................................... 417 Form
DocumentTimeline .............................................. 696 select by selector ............................................... 373 define multiple .................................................. 418 access to .............................................................. 459
DOM ........................................................................... 357 setAttribute() ...................................................... 403 helper function .................................................. 423 element access .................................................. 463
access CSS classes ............................................. 406 Encapsulation ............................................... 252, 728 pass arguments ................................................ 420 event ............................................................ 434, 581
API .......................................................................... 362 enumerable ............................................................. 247 register ................................................................. 577 reset ....................................................................... 472
change the value of an attribute ............... 405 Error ............................................................................ 203 remove .................................................................. 422 submit .................................................................. 472
create and add attribute nodes .................. 406 catch and handle .............................................. 202 every() ........................................................................ 775 validate ................................................................ 475
event handler ..................................................... 411 logic ........................................................................ 200 Exception ................................................................. 201 Formatting dates and times ............................. 714
event listener ...................................................... 411 trigger .................................................................... 205 Exception Handling ............................................. 201 Formatting numeric values ............................. 717
examine in browser ......................................... 361 Error handling ........................................................ 201 Executable machine code file ............................. 35 FormData ................................................................. 546
manipulation ..................................................... 392 Escape character ...................................................... 99 for-of loop ............................................................... 317

972 973
Index Index

Fragment identifier .............................................. 499 Git (Cont.) I iPad ............................................................................ 877


Front end ..................................................................... 48 index ............................................................ 952, 965 iPhone ....................................................................... 877
Function ............................................................ 66, 171 local working copy ........................................... 952 i18n ............................................................................. 708 isSealed() .................................................................. 268
anonymous ........................................................ 169 merge ..................................................................... 965 IDE .................................................................................. 61 Iterable ...................................................................... 820
borrowing ........................................................... 355 pull .......................................................................... 965 if statement ............................................................. 133 Iteration ................................................................... 148
call .......................................................................... 171 push ........................................................................ 965 if-else-if-else branch ............................................ 136 Iterator ............................................................. 317, 816
call stack .............................................................. 190 remote repository ............................................. 965 Immediately Invoked Function
call with a parameter ..................................... 172 repository ............................................................ 965 Expression (IIFE) ............................................... 783 J
call with multiple parameters ..................... 174 snapshot ............................................................... 951 Imperative programming ................................. 766
closure .................................................................. 783 staging area .............................................. 952, 965 Implementation ............................................. 41, 362 Java ...................................................................... 46, 877
code ....................................................................... 191 working directory ................................... 952, 965 import() ..................................................................... 796 Java Runtime Environment (JRE) ...................... 38
declaration ......................................................... 169 workspace ............................................................ 965 Increment operator ............................................. 114 JavaScript library ..................................................... 77
define .................................................................... 168 Global jQuery method ......................................... 585 Indexed Database API ......................................... 654 JavaScript Object Notation ...................... 519, 524
define with a parameter ................................ 172 Google Maps API .................................................... 685 IndexedDB API ....................................................... 654 JIT ................................................................................... 38
define with multiple parameters ............... 173 Gradient indexOf() ........................................................ 290, 308 Johnny Five ...................................................... 52, 925
expression ........................................................... 169 linear ...................................................................... 611 Infinite loop ............................................................ 164 jQuery
methods ............................................................... 353 radial ..................................................................... 611 Infinity ......................................................................... 98 access attributes .............................................. 571
named ................................................................... 169 Grammar .................................................................... 85 Information hiding .................................... 728, 782 access content ................................................... 566
parameters ......................................................... 172 Graph database ...................................................... 654 Inheritance ........................................... 265, 726, 729 access CSS properties ..................................... 572
signature ............................................................. 173 Grunt .......................................................................... 931 innerHTML .............................................................. 392 Ajax ....................................................................... 584
variadic ................................................................ 178 installing plug-ins ............................................ 933 innerText ................................................................. 392 Ajax events ......................................................... 587
Functional Programming .................................. 765 using plug-ins ..................................................... 933 Input ............................................................................. 43 attribute filter selectors ....................... 561, 563
Functional programming [Link] ............................................................... 932 Input and output basic filter selectors ............................... 561, 562
difference to imperative programming ... 767 Gulp ............................................................................ 935 blocking ............................................................... 831 basic selectors ................................................... 561
filter values ......................................................... 771 [Link] .................................................................. 935 non-blocking ...................................................... 833 child filter selectors ................................ 561, 564
iterate ................................................................... 767 Input dialog ................................................................ 76 content filter selectors .......................... 561, 563
language .............................................................. 765 H insertBefore() .......................................................... 394 embed ................................................................... 556
map values ......................................................... 770 Instance .................................................................... 726 embed via a CDN ............................................. 557
reduce multiple values to one value ......... 773 Hashbang URL ........................................................ 503 Interface .................................................................... 362 event methods .................................................. 577
Hello World example ............................................. 64 Interface element .................................................... 50 event object ........................................................ 582
G Hexadecimal notation .......................................... 96 Intermediate language .......................................... 35 filter elements ................................................... 569
Hexadecimal number ........................................... 96 Internationalisierung form events ........................................................ 581
Garbage collection ...................................... 319, 324 High-level programming language ................. 33 locales ................................................................... 709 form filter selectors ................................ 561, 564
General event ......................................................... 578 Hint dialog ................................................................. 76 sub tags ................................................................ 709 general events ................................................... 578
Generator ................................................................. 820 History ............................................................... 46, 503 Internationalization global jQuery methods .................................. 585
infinite .................................................................. 822 pushState() .......................................................... 504 extension subtag .............................................. 710 hierarchy selectors ................................. 561, 562
parameter ........................................................... 823 replaceState() ........................................... 504, 506 language subtag ............................................... 709 keyboard events ............................................... 581
Geolocation ............................................................. 682 history ........................................................................ 502 language tag ...................................................... 709 load HTML data via Ajax ............................. 588
API .......................................................................... 682 History API ............................................................... 503 region subtag ..................................................... 709 load JSON data via Ajax ................................ 590
get ............................................................................... 251 HTML ............................................................................ 55 script subtag ...................................................... 710 load XML data via Ajax ................................ 589
getElementById() .................................................. 364 HTML element ................................................ 66, 398 variant subtag ................................................... 710 modify content ................................................. 566
getElementsByClassName() .............................. 367 HTML event handler ............................................ 411 Internationalization (i18n) ............................... 708 mouse events ..................................................... 579
getElementsByName() ........................................ 372 HTML5 app ............................................................... 878 Internationalization API .................................... 710 navigate between elements ......................... 573
getElementsByTagName() ................................. 370 HTML5 application ................................................. 51 Internet media type ................................................ 68 register event listener .................................... 577
Getter method ............................................. 251, 785 HTTP ........................................................................... 513 Internet of Things (IoT) ............................... 52, 909 respond to events ............................................ 576
Git ................................................................................ 950 HTTP protocol ......................................................... 639 Interpret ...................................................................... 37 select elements .................................................. 561
branch ................................................................... 965 HTTP request ........................................................... 513 Interpreter .................................................................. 35 selected elements ............................................. 559
checkout .............................................................. 965 HTTP response ........................................................ 513 [Link] ............................................................. 711 selected nodes ................................................... 559
clone ...................................................................... 965 Hybrid app ............................................................... 879 [Link] .......................................... 711 use effects ........................................................... 575
commit ................................................................. 965 Hybrid application ................................................ 879 [Link] ............................................. 711 visibility filter selectors ........................ 561, 563
fork ......................................................................... 965 Hypertext Transfer Protocol ............................ 513 Ionic ............................................................................ 883 jQuery method ...................................................... 558
HEAD ..................................................................... 965 iOS .................................................................................. 51 jQuery object .......................................................... 558

974 975
Index Index

jQuery() ..................................................................... 558 Loop (Cont.) Module augmentation ....................................... 789 NPM Registry ......................................................... 836
JRE .................................................................................. 38 nested .................................................................... 153 Module design pattern ....................................... 783 null ............................................................................. 110
JSON ........................................................ 519, 524, 527 outer ...................................................................... 153 Module test ............................................................. 938 Nullish coalescing operator ............................. 122
JSON format ............................................................ 524 tail-controlled .......................................... 149, 158 Modulo ...................................................................... 114 Number ....................................................................... 95
JSON with padding ............................................... 550 terminate prematurely ................................... 160 MongoDB ....................................................... 654, 859 definition ............................................................... 95
[Link]() ............................................ 527, 528 Loop body ....................................................... 149, 155 Mouse event ................................................. 427, 579 value range ........................................................... 97
JSONP ......................................................................... 550 Loose augmentation ............................................ 790 MouseEvent ............................................................ 429 NumberFormat ..................................................... 717
JSX ............................................................................... 888 Loose typing .............................................................. 95 Multidimensional array ..................................... 106 [Link] .......................................................................... 898
Jump label ................................................................ 165 lowerCamelCase notation ................................... 92 Multilingual applications .................................. 708 Installation ......................................................... 899
Just-in-Time Compiler ........................................... 38 Multiple selection list ......................................... 470 Packaging ........................................................... 901
M read ........................................................................ 470
K Multiplication ........................................................ 114 O
Machine code ............................................................ 33 Multipurpose Internet Mail
Keyboard event ........................................... 431, 581 Machine language ................................................... 33 Extension (MIME) ............................................... 68 Object ............................................................... 109, 726
KeyboardEvent ...................................................... 431 Main thread ............................................................. 678 Multithreaded ........................................................ 678 array-like ............................................................. 177
KeyframeEffect ...................................................... 696 Map ................................................................... 272, 314 servers ................................................................... 831 behavior .............................................................. 236
Key-value pair ........................................................ 314 add elements ...................................................... 315 Multiway branch ................................................... 142 bind ....................................................................... 353
Key-value stores .................................................... 654 delete all key-value pairs ............................... 315 definition ............................................................ 109
Keyword ...................................................................... 88 delete individual key-value pairs ............... 315 N extract values .................................................... 298
Kotlin ......................................................................... 877 determine elements for key .......................... 315 first class ............................................................. 765
map() .......................................................................... 770 Named function .................................................... 169 freeze .................................................................... 269
L Markup language .................................................... 59 Namespace .............................................................. 779 global .................................................................... 488
Math ........................................................................... 328 Namespace design pattern ............................... 779 intercept access ................................................ 824
Label ........................................................................... 165 Maximum value of numbers ............................. 98 NaN ................................................................................ 98 iterable ................................................................. 819
Language subtag ................................................... 709 MEAN ......................................................................... 866 Native application ...................................... 877, 883 [Link]() ................................................... 733
Language tag ........................................................... 709 stack ....................................................................... 866 NativeScript ............................................................ 883 [Link]() .............................. 258
lastChild .................................................................... 383 Member ..................................................................... 250 Navigator .................................................................. 508 [Link]() ................................. 258
lastElementChild ................................................... 383 Member operator .................................................. 250 Negation operator ................................................ 117 [Link]() ................................................... 269
lastIndexOf() ........................................................... 308 Mercurial .................................................................. 950 Nested namespacing ........................................... 782 [Link]() ........ 248
let .................................................................................... 85 Method ...................................................................... 109 Netscape ...................................................................... 46 [Link]() ................................ 241
Library .......................................................................... 50 borrowing .................................................. 355, 369 nextElementSibling ............................................. 386 [Link]() ....................................... 268
LIFO principle ......................................................... 287 call stack ...................................................... 80, 190 nextSibling .............................................................. 385 [Link]() .............................................. 269
Literal ......................................................................... 113 signature .............................................................. 173 Node ........................................................................... 357 [Link]() .......................... 267
Literal notation ...................................................... 237 static ...................................................................... 760 Node list .................................................................... 368 [Link]() ....................................................... 268
LiveScript .................................................................... 46 Microcontroller ...................................................... 909 static ...................................................................... 369 prevent extensions .......................................... 267
Local browser storage ......................................... 647 Middleware .............................................................. 854 Node type ................................................................. 358 seal ........................................................................ 268
Locales ....................................................................... 709 function ................................................................ 854 [Link] ....................................................................... 357 state ...................................................................... 236
localStorage ............................................................. 647 Minimum value of numbers .............................. 97 create packages ................................................ 838 Object destructuring ........................................... 298
Location .................................................................... 499 Mobile application instal packages ................................................. 835 Object diagram ...................................................... 726
assign() ................................................................. 500 hybrid .................................................................... 879 install packages globally .............................. 835 Object instance ...................................................... 726
href ......................................................................... 501 native ..................................................................... 877 install packages locally ................................. 835 create .................................................................... 748
reload() ................................................................. 501 Mobile web application ...................................... 878 modules ............................................................... 831 Object literal notation ........................................ 237
replace() ............................................................... 501 Mocha ................................................................ 46, 945 [Link] Package Manager (NPM) .............. 834 Object method ....................................................... 109
Logical AND assignment operator ................. 130 Modifier .................................................................... 344 NPM ....................................................................... 834 add ......................................................................... 256
Logical assignment operators ......................... 130 Modifying the CSS of an element ................... 369 Package configuration file ........................... 838 create via bracket notation ......................... 257
Logical nullish assignment operator ............ 130 Module packages .............................................................. 831 create via dot notation ................................. 256
Logical OR assignment operator .................... 130 default export .................................................... 794 use packages ...................................................... 836 create via helper methods ............................ 258
Long polling ............................................................ 632 define ..................................................................... 794 Nonblocking I/O .................................................... 833 delete .................................................................... 260
Look-and-feel .......................................................... 883 export .................................................................... 794 Nonrelational database ...................................... 654 output .................................................................. 262
Loop .................................................................. 133, 148 import ................................................................... 795 NPM ............................................................................ 834 overwrite ............................................................. 256
head-controlled ...................................... 148, 155 import dynamically ......................................... 796 npm init .................................................................... 838 Object orientation ................................................ 725
inner ...................................................................... 153 named export ..................................................... 794 npm install .............................................................. 835 basic principles ................................................. 725

976 977
Index Index

Object orientation (Cont.) Parent class .............................................................. 732 prompt() ...................................................................... 76 Regular expression (Cont.)
class syntax ........................................................ 731 Parent constructor ................................................ 754 Property .................................................................... 109 define exact number of occurrences ........ 340
class-based .......................................................... 727 parentElement ........................................................ 379 static ...................................................................... 762 define minimum and maximum
prototypical .............................................. 727, 731 parentNode .............................................................. 379 Property attribute ....................................... 246, 739 number of occurrences ............................. 340
pseudoclassical ................................................. 731 Parsing ......................................................................... 70 Prototype .............................................. 241, 727, 732 define minimum number of
Object property ..................................................... 109 Password field, read .............................................. 465 Prototype chain ........................................... 242, 736 occurrences ................................................... 340
add ......................................................................... 256 Path ............................................................................. 604 Prototype programming ................................... 727 define optional occurrences ........................ 339
create via bracket notation ......................... 257 Pattern ....................................................................... 783 Prototype-based programming ...................... 727 groups .................................................................. 345
create via dot notation .................................. 256 Polling ........................................................................ 631 Prototypical object orientation ... 727, 731, 732 named groups ................................................... 346
create via helper methods ............................ 258 Polymorphic ............................................................ 731 calling methods of the prototype .............. 737 replace occurrence .......................................... 347
delete ..................................................................... 260 Polymorphism ............................................. 726, 731 inherit methods and properties ................. 733 search for specific strings ............................. 346
output ................................................................... 262 pop() ............................................................................ 279 overwrite methods .......................................... 735 Relational database ............................................. 654
overwrite ............................................................. 256 PopStateEvent ........................................................ 506 Proxy .......................................................................... 824 Relational operator .............................................. 125
Object store Preflight request .................................................... 549 Pseudoclassical object orientation ...... 731, 739 Remainder operator ............................................ 114
add objects .......................................................... 657 Preflight response ................................................. 549 create object instances .................................. 739 Remote branch ...................................................... 959
create .................................................................... 657 Prematurely terminating loop iterations ... 162 define methods and properties .................. 740 Remote repository ............................................... 950
delete objects ..................................................... 661 Presentation Layer .................................................. 58 derive from objects .......................................... 740 removeAttribute() ................................................ 406
read objects ........................................................ 661 preventDefault() .......................................... 447, 452 Pseudocode ................................................................ 44 removeChild() ........................................................ 397
update objects ................................................... 663 previousElementSibling ..................................... 386 Pseudocode technique .......................................... 41 removeEventListener() ...................................... 422
use cursor ............................................................ 664 previousSibling ...................................................... 385 push() ......................................................................... 275 Render .......................................................................... 59
[Link]() ................................... 238, 262, 263 Private methods .................................................... 750 Pyramid of doom .................................................. 803 Rendering context ............................................... 600
[Link]() .................................................. 262, 263 Private properties ................................................. 750 Repetition ................................................................ 133
[Link]() .............................................. 262, 263 Private property ..................................................... 252 Q REPL ........................................................................... 833
Object-based programming language .......... 727 Program ...................................................................... 32 replaceChild() ......................................................... 394
Objective-C .............................................................. 877 native ....................................................................... 36 Query string ............................................................ 499 reportValidity() ..................................................... 482
Object-oriented programming ..... 242, 725, 766 Program flowchart .................................................. 41 querySelector() ....................................................... 373 Repository ............................................................... 949
Octal notation ........................................................... 96 Programming querySelectorAll() ................................................. 373 local ....................................................................... 950
Octal number ............................................................ 96 asynchronous ..................................................... 799 Queue .............................................................. 272, 288 remote .................................................................. 950
onload ....................................................................... 416 classless ................................................................ 727 QUnit ......................................................................... 939 Request ..................................................................... 513
onreadystatechange ............................................ 534 event-driven ........................................................ 409 Request queue ....................................................... 832
Operation .................................................................... 43 functional ............................................................ 765 R requestAnimationFrame() ................................ 618
Operator ................................................................... 113 imperative ........................................................... 766 reset() ........................................................................ 472
arithmetic ........................................................... 114 object-oriented ........................................ 725, 766 Radio button, read ................................................ 467 Responsive app ..................................................... 878
binary .......................................................... 114, 117 prototype-based ................................................ 727 RangeError ............................................................... 203 Responsive web design ...................................... 878
bitwise .................................................................. 124 prototypical ........................................................ 727 Raspberry Pi ............................................................ 921 Rest parameter ...................................................... 177
logical ................................................................... 117 Programming language ................................. 33, 59 React Native .................................................. 877, 883 Rest properties ...................................................... 304
logical AND assignment ................................ 130 class-based .......................................................... 727 Read file information .......................................... 848 Return code ............................................................ 180
logical nullish assignment ........................... 130 compiled ................................................................. 35 Readable stream .......................................... 866, 868 Return value
logical OR assignment ................................... 130 functional ............................................................ 765 Read-eval-print loop ............................................ 833 multiple ............................................................... 182
overloaded .......................................................... 117 interpreted ............................................................. 35 Redis ........................................................................... 654 Revealing module design pattern ................. 786
unary ........................................................... 113, 117 object-based ........................................................ 727 reduce() ..................................................................... 773 Revealing module pattern ................................ 787
Optional chaining operator .................... 128, 366 ProgressEvent ......................................................... 671 reduceRight() .......................................................... 775 reverse() .................................................................... 284
OR operator ............................................................. 117 Promise ..................................................................... 804 Refactoring .............................................................. 938 RFC3986 ................................................................... 670
Output .......................................................................... 43 [Link]() ............................................................. 808 ReferenceError ....................................................... 203 Rich internet application ..................................... 47
[Link]() .............................................. 810 RegExp Root node ................................................................ 359
P [Link]() .......................................................... 811 exec() ........................................................... 329, 343 Routing ..................................................................... 853
[Link]() ................................. 805 test() ............................................................. 329, 330 RTE ................................................................................. 37
Package ..................................................................... 779 [Link]() ............................... 806 Region subtag ......................................................... 709 Runtime environment (RTE) .............................. 37
Package configuration file ................................ 838 [Link]() .................................. 805 Regular expression Runtime error ........................................................ 199
[Link] ............................................................ 838 [Link]() ......................................................... 809 define any number of occurrences ............ 339
properties ............................................................ 839 [Link]() ...................................................... 812 define at least one occurrence .................... 339
Parameter ...................................................... 172, 173 [Link]() ................................................... 812

978 979
Index Index

S Source code (Cont.) String (Cont.) Test case ................................................................... 936


display ..................................................................... 74 multiline .............................................................. 102 Test fixture .............................................................. 939
Scalable Vector Graphics ................................... 599 show in Chrome .................................................. 74 placeholder ......................................................... 101 Test framework ........................................................ 61
Schema ...................................................................... 657 show in Firefox .................................................... 74 replace() ..................................................... 329, 347 Test program .......................................................... 936
Scope .......................................................................... 192 show in Microsoft Edge .................................... 76 search .................................................................... 308 Test-driven development ................................. 937
chain ............................................................ 192, 193 show in Opera ...................................................... 74 search for occurrences ................................... 347 Text field, read ....................................................... 465
dynamic ............................................................... 192 show in Safari ...................................................... 74 search() ................................................................. 329 Text node ................................................................. 360
lexical .................................................................... 192 Source control system ........................................... 61 split ........................................................................ 348 text/ecmascript ....................................................... 68
static ...................................................................... 192 Source file ................................................................... 34 split() ..................................................................... 329 text/javascript .......................................................... 68
Scope chain ............................................................. 193 Source text ................................................................. 34 structure .............................................................. 306 textContent ............................................................ 391
Screen ........................................................................ 510 Speech output ......................................................... 692 substr() .................................................................. 312 this ..................................................................... 192, 194
Screen Orientation API ....................................... 511 Speech recognition ............................................... 694 substring() ........................................................... 312 constructor function ...................................... 196
Script subtag ........................................................... 710 SpeechRecognition ............................................... 691 String concatenation ........................................... 101 global function ................................................. 196
Search string ........................................................... 499 SpeechSynthesis .................................................... 691 String operator ....................................................... 116 object method ................................................... 196
Secure Sockets Layer ........................................... 641 splice() .............................................................. 277, 281 Strong typing ............................................................. 95 Thread ....................................................................... 678
Selection list Spread operator ..................................................... 184 Style language ........................................................... 59 throw ......................................................................... 205
fill with values ................................................... 471 Spread properties .................................................. 305 Sub tags ..................................................................... 709 Tight augmentation ............................................ 790
read ........................................................................ 469 Square curve ............................................................ 607 Subclass .................................................................... 730 Top level await ....................................................... 814
Selection operator ................................................ 140 drawing ................................................................ 607 Sublime Text .............................................................. 60 Transaction ............................................................. 658
Sensor ........................................................................ 909 Stack .................................................................. 272, 287 submit() .................................................................... 472 Transform streams .............................................. 867
Serialize XML data ................................................ 523 Stack trace .................................................................. 80 Subobject .................................................................. 730 Transformation matrix ..................................... 615
Server ......................................................................... 513 Standard variable, global ...................................... 90 Subtraction .............................................................. 114 Trap ............................................................................ 825
Server side .................................................................. 48 Start/stop checkpoints .......................................... 42 Subtype ..................................................................... 730 Tree representation ............................................. 357
Server-sent events ...................................... 631, 635 State ............................................................................ 726 Subversion ............................................................... 949 True ............................................................................ 103
Session storage ...................................................... 647 Stateless protocol .................................................. 639 Sun ................................................................................. 46 try ............................................................................... 202
Set ............................................................. 251, 272, 321 Statement ............................................................ 43, 73 Superclass ...................................................... 730, 732 Two-dimensional array ...................................... 106
add elements ...................................................... 321 conditional .......................................................... 133 Superobject ............................................................. 730 TypeError ................................................................. 203
create .................................................................... 321 destructuring ...................................................... 294 Supertype ................................................................. 730 typeof ........................................................................ 233
delete all elements ........................................... 322 named ................................................................... 166 SVG format .............................................................. 620
delete individual elements ........................... 322 static ........................................................................... 760 Swift ............................................................................ 877 U
setAttributeNode() ..................................... 403, 406 Static methods ........................................................ 760 Switch branch ......................................................... 142
setInterval() ............................................................. 498 Static property ........................................................ 762 Symbol ...................................................................... 112 UI .......................................................................... 49, 409
Setter .......................................................................... 251 Step ............................................................................... 32 [Link] ...................................................... 266 UI component .................................................... 50, 77
setTimeout() ........................................................... 498 stopPropagation() ................................................. 447 Syntax ........................................................................... 85 UIEvent ..................................................................... 435
shift() .......................................................................... 280 Storage ....................................................................... 647 Syntax error .................................................. 198, 203 UML ............................................................................ 726
Shopping cart ............................................... 644, 653 StorageEvent ........................................................... 650 System under test ................................................. 936 undefined ................................................................ 110
Side effect ................................................................. 766 Store value in variables ......................................... 85 Unidirectional communication ..................... 631
Single-page application ...................................... 503 Streams T Unified modeling language (UML) ................ 726
Single-threaded server ........................................ 832 flowing mode ..................................................... 869 Uniform resource identifier (URI) ................. 670
slice() .......................................................................... 282 paused mode ...................................................... 869 Tablet ......................................................................... 877 Uniform resource locator (URL) ..................... 670
Smartphone ............................................................ 877 piping .................................................................... 870 Tag function ............................................................ 188 Uniform resource name (URN) ....................... 670
Smartwatch ................................................................ 52 read data .............................................................. 868 Tagged template .......................................... 103, 188 Unit test ................................................................... 936
Socket connection ................................................ 633 write data ............................................................ 869 Target phase ............................................................ 439 unshift() .................................................................... 276
Software ....................................................................... 32 Strict Typing .............................................................. 95 Task ............................................................................. 932 UpperCamelCase notation ............... 93, 239, 243
Software library ........................................................ 50 String .................................................................. 98, 116 Template string ..................................................... 101 URI .............................................................................. 670
some() ........................................................................ 775 compare ............................................................... 712 expressions ......................................................... 102 error ...................................................................... 203
Sort array definition ............................................................... 98 multiline .............................................................. 102 URL ............................................................................. 670
arrays with objects .......................................... 285 determine length .............................................. 307 placeholder ......................................................... 101 URN ............................................................................ 670
comparison function ...................................... 284 escaping ................................................................. 99 use .......................................................................... 101 Use effect ................................................................. 575
sort() ........................................................................... 284 expressions .......................................................... 102 Tessel .................................................................. 52, 916 User interface ........................................... 49, 50, 409
Source code ................................................................ 34 extract parts ....................................................... 310 control LEDs ....................................................... 917 event ..................................................................... 435
automated testing ........................................... 936 match() ................................................................. 329 Test anything protocol ....................................... 948

980 981
Index

V Web of Things ................................................. 52, 909


Web page ..................................................................... 47
Validate form input ............................................. 475 print ....................................................................... 496
Validation ................................................................... 49 search for text .................................................... 496
native .................................................................... 475 Web Socket API ............................................. 631, 633
Value assignment .................................................... 86 Web Speech API ...................................................... 691
Value range of numbers ........................................ 97 Web Storage API ..................................................... 647
var .................................................................................. 85 Web view ................................................................... 880
Variable ........................................................................ 85 Web Worker API ..................................................... 679
define ....................................................................... 85 WebGL ........................................................................ 600
Variable declaration ................................................ 85 WebGLRenderingContext .................................. 601
Variable initialization ............................................ 86 Website ........................................................................ 47
Variable name WebStorm .................................................................. 62
allowed characters ............................................. 91 While loop ................................................................ 155
already assigned ................................................. 90 Widget .............................................................. 518, 883
case sensitivity ..................................................... 92 window ...................................................................... 487
meaningful names ............................................. 93 Windows Mobile ...................................................... 51
valid .......................................................................... 88 World Wide Web Consortium (W3C) ... 362, 630
Variant subtag ........................................................ 710 Wrapper object ....................................................... 329
VCS writable ...................................................................... 247
centralized .......................................................... 949 Writable streams ......................................... 866, 869
decentralized ..................................................... 949
Version control system (VCS) .......................... 949 X
Version management ......................................... 949
Version management system ......................... 949 XML ................................................................... 518, 519
Visual Studio Code .................................................. 62 parse ...................................................................... 522
serialize ................................................................. 523
W XML object, convert to strings ......................... 523
XML schema ............................................................ 519
WeakMap ................................................................. 319 XMLHttpRequest ................................................... 529
WeakSet .................................................................... 324 XMLSerializer .......................................................... 523
Wearables .................................................................... 52
Web Animation API ............................................. 695 Y
Web application ........................................................ 47
Web Hypertext Application Technology yield ............................................................................ 821
Working Group ................................................. 630

982
Build and deepen your coding knowledge
from the top programming experts!

Philip Ackermann is CTO of Cedalo GmbH and author of


several reference books and technical articles on Java, Java-
Script and web development. His focus is on the design and
development of [Link] projects in the areas of Industry 4.0
and Internet of Things.

Philip Ackermann
JavaScript: The Comprehensive Guide
982 pages, 2022, $59.95 We hope you have enjoyed this reading sample. You may recommend or pass it
ISBN 978-1-4932-2286-5 on to others, but only in its entirety, including all pages. This reading sample and
all its parts are protected by copyright law. All usage and exploitation rights are
[Link]/5554 reserved by the author and the publisher.

You might also like