Javascript
Javascript
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”
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.
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)
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).
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.
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
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.
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
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.
Figure 2.18 Show Source Code in Chrome Figure 2.21 Show Source Code in Opera
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).
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');
}
Depending on the browser, the result should be similar to that shown in Figure 2.30.
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.
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
556 557
10 Simplifying Tasks with jQuery 10.1 Introduction
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)
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
#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
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
562 563
10 Simplifying Tasks with jQuery 10.2 Working with the DOM
: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.
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.
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.
566 567
10 Simplifying Tasks with jQuery 10.2 Working with the DOM
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
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"
570 571
10 Simplifying Tasks with jQuery 10.2 Working with the DOM
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
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
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 });
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)
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
586 587
10 Simplifying Tasks with jQuery 10.4 Creating Ajax Requests
'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:
쐍 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
594 595
10 Simplifying Tasks with jQuery 10.5 Summary
Pure JavaScript:
fetch(url)
.then(response => {})
.catch(error => {});
Pure JavaScript:
fetch('url', {
method: 'POST',
body: data,
})
.then(response => {})
.catch(error => {});
596 597
Contents
2 Getting Started 55
7
Contents Contents
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
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
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
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
24
Index
969
Index Index
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
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
980 981
Index
982
Build and deepen your coding knowledge
from the top programming experts!
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.