12,99 €
The concise and digestible get-started guide to JavaScript programming JavaScript Essentials For Dummies is your quick reference to all the core concepts about JavaScript--the dynamic scripting language that is often the final step in creating powerful websites. This no-nonsense book gets right to the point, eliminating review material, wordy explanations, and fluff. Find out all you need to know about the foundations of JavaScript, swiftly and crystal clear. Perfect for a brush-up on the basics or as an everyday desk reference on the job, this is the reliable little book you can always turn to for answers. * Get a quick and thorough intro to the basic concepts of coding with JavaScript * Review what you've already learned or pick up essential new skills * Add interactive features to websites with JavaScript programming * Keep this concise reference book handy for jogging your memory as you work This book is to the point, focusing on the key topics you need to know about this popular programming language. Great for supplementing classroom learning, reviewing for a certification, or staying knowledgeable on the job.
Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 200
Cover
Title Page
Copyright
Introduction
About This Book
Foolish Assumptions
Icons Used in This Book
Where to Go From Here
Chapter 1: JavaScript: The Big Picture
Adding JavaScript Code to a Web Page
What You Need to Get Started
Dealing with Two Exceptional Cases
Commenting Your Code
Moving to External JavaScript Files
Chapter 2: Programming with Variables
Getting Your Head around Variables
Naming Variables: Rules and Best Practices
Understanding Literal Data Types
Chapter 3: Building Expressions
Understanding How Expressions Are Structured
Creating Numeric Expressions
Building String Expressions
Building Comparison Expressions
Building Logical Expressions
Understanding Operator Precedence
Chapter 4: Controlling the Flow of JavaScript
Decision-Making with if Statements
Branching with if…else Statements
Understanding the Value of Code Looping
Working with while Loops
Working with for Loops
Working with do…while Loops
Chapter 5: Harnessing the Power of Functions
Getting to Know the Function Structure
Making a Function Call
Passing One or More Values to a Function
Getting a Value from a Function
Working with Anonymous Functions
Working with Arrow Functions
Chapter 6: Coding the Document Object Model
Getting Familiar with Objects
Introducing the Document Object Model
Specifying Elements in Your Code
Touring the DOM with Code
Adding, Modifying, and Removing Elements
Using Code to Mess Around with CSS
Using Code to Tweak HTML Attributes
Listening for Page Events
Chapter 7: Working with Arrays
What Is an Array?
Declaring an Array
Populating an Array
Iterating Arrays
Manipulating Arrays
Chapter 8: Coding Strings and Dates
Manipulating Strings
Dealing with Dates and Times
Chapter 9: Debugging JavaScript
Laying Out Your Debugging Tools
Debugging 101: Using the Console
Putting Your Code into Break Mode
Stepping Through Your Code
Chapter 10: Dealing with Form Data
Coding Text Fields
Programming Checkboxes
Coding Radio Buttons
Programming Selection Lists
Working with Form Events
Handling Form Data
Chapter 11: Ten JavaScript Debugging Strategies
Get Thee to Your Dev Tools
The Console Is Your Best Debugging Friend
Give Your Code a Break(point)
Step Through Your Code
Monitor Variable and Object Property Values
Indent Your Code
Break Down Complex Tasks
Break Up Long Statements
Comment Out Problem Statements
Use Comments To Document Your Scripts
Index
About the Author
Advertisement Page
Connect with Dummies
End User License Agreement
Chapter 2
TABLE 2-1 Common JavaScript Escape Sequences
Chapter 3
TABLE 3-1 The JavaScript Arithmetic Operators
TABLE 3-2 The JavaScript Arithmetic Assignment Operators
TABLE 3-3 The JavaScript Comparison Operators
TABLE 3-4 The JavaScript Logical Operators
TABLE 3-5 The JavaScript Order of Precedence for Operators
Chapter 7
TABLE 7-1 Useful Array Methods
Chapter 8
TABLE 8-1 String Object Methods for Searching for Substrings
TABLE 8-2 String Object Methods for Extracting Substrings
TABLE 8-3 Arguments Associated with the Date Object
TABLE 8-4 Date Object Methods That Extract Date Values
TABLE 8-5 Date Object Methods That Set Date Values
Chapter 1
FIGURE 1-1: This “alert” message appears when you open the HTML file containing...
FIGURE 1-2: When you open the file, the text displays the date and time the fil...
FIGURE 1-3: This page uses an external JavaScript file to display a footer mess...
Chapter 2
FIGURE 2-1: The browser substituting the current value of a variable.
FIGURE 2-2: The script first prompts for the user’s first name.
FIGURE 2-3: The script then uses the name to display a personalized welcome mes...
FIGURE 2-4: Using the
\n
escape sequence enables you to format text so that it ...
Chapter 4
FIGURE 4-1: Set up your
while
expression so that the prompting stops when the u...
FIGURE 4-2: This script uses the current value of the
counter
variable to custo...
FIGURE 4-3: The decrementing value of the rank variable is used to create a rev...
Chapter 5
FIGURE 5-1: An example of calling a function when the
<script>
tag is p...
FIGURE 5-2: An example of calling a function after the page has loaded.
FIGURE 5-3: An example of calling a function in response to an event.
FIGURE 5-4: The output includes the return value of the custom function calcula...
Chapter 6
FIGURE 6-1: This script displays the
document.location
property in a console me...
FIGURE 6-2: The web page code as a hierarchy.
FIGURE 6-3: The output of the script that iterates over the
div
elements.
FIGURE 6-4: The value of the
bodyChildElements
variable displayed in the consol...
FIGURE 6-5: This code uses the
add
() method to add the class named
my-class
to ...
FIGURE 6-6: The
click
event callback function adds some HTML and text to the
di
...
FIGURE 6-7: The
keypress
event callback function uses
e.which
to write the nume...
Chapter 9
FIGURE 9-1: The HTML viewer, such as Chrome’s Elements tab, enables you to insp...
FIGURE 9-2: When you invoke break mode, the web browser displays its debugging ...
FIGURE 9-3: In the browser’s debugging tool, click a line number to set a break...
Chapter 10
FIGURE 10-1: The script converts the
input
element’s default text to all-lowerc...
FIGURE 10-2: A form used to gather user settings for the page.
Cover
Table of Contents
Title Page
Copyright
Begin Reading
Index
About the Author
i
ii
1
2
3
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
105
106
107
108
109
110
111
112
113
114
115
117
118
119
120
121
122
123
124
125
126
127
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
JavaScript® Essentials For Dummies®
Published by: John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030-5774, www.wiley.com
Copyright © 2024 by John Wiley & Sons, Inc., Hoboken, New Jersey
Published simultaneously in Canada
No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of the 1976 United States Copyright Act, without the prior written permission of the Publisher. Requests to the Publisher for permission should be addressed to the Permissions Department, John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030, (201) 748-6011, fax (201) 748-6008, or online at http://www.wiley.com/go/permissions.
Trademarks: Wiley, For Dummies, the Dummies Man logo, Dummies.com, Making Everything Easier, and related trade dress are trademarks or registered trademarks of John Wiley & Sons, Inc. and may not be used without written permission. JavaScript is a registered trademark of Oracle and/or its affiliates. All other trademarks are the property of their respective owners. John Wiley & Sons, Inc. is not associated with any product or vendor mentioned in this book.
LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: WHILE THE PUBLISHER AND AUTHORS HAVE USED THEIR BEST EFFORTS IN PREPARING THIS WORK, THEY MAKE NO REPRESENTATIONS OR WARRANTIES WITH RESPECT TO THE ACCURACY OR COMPLETENESS OF THE CONTENTS OF THIS WORK AND SPECIFICALLY DISCLAIM ALL WARRANTIES, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. NO WARRANTY MAY BE CREATED OR EXTENDED BY SALES REPRESENTATIVES, WRITTEN SALES MATERIALS OR PROMOTIONAL STATEMENTS FOR THIS WORK. THE FACT THAT AN ORGANIZATION, WEBSITE, OR PRODUCT IS REFERRED TO IN THIS WORK AS A CITATION AND/OR POTENTIAL SOURCE OF FURTHER INFORMATION DOES NOT MEAN THAT THE PUBLISHER AND AUTHORS ENDORSE THE INFORMATION OR SERVICES THE ORGANIZATION, WEBSITE, OR PRODUCT MAY PROVIDE OR RECOMMENDATIONS IT MAY MAKE. THIS WORK IS SOLD WITH THE UNDERSTANDING THAT THE PUBLISHER IS NOT ENGAGED IN RENDERING PROFESSIONAL SERVICES. THE ADVICE AND STRATEGIES CONTAINED HEREIN MAY NOT BE SUITABLE FOR YOUR SITUATION. YOU SHOULD CONSULT WITH A SPECIALIST WHERE APPROPRIATE. FURTHER, READERS SHOULD BE AWARE THAT WEBSITES LISTED IN THIS WORK MAY HAVE CHANGED OR DISAPPEARED BETWEEN WHEN THIS WORK WAS WRITTEN AND WHEN IT IS READ. NEITHER THE PUBLISHER NOR AUTHORS SHALL BE LIABLE FOR ANY LOSS OF PROFIT OR ANY OTHER COMMERCIAL DAMAGES, INCLUDING BUT NOT LIMITED TO SPECIAL, INCIDENTAL, CONSEQUENTIAL, OR OTHER DAMAGES.
For general information on our other products and services, please contact our Customer Care Department within the U.S. at 877-762-2974, outside the U.S. at 317-572-3993, or fax 317-572-4002. For technical support, please visit https://hub.wiley.com/community/support/dummies.
Wiley publishes in a variety of print and electronic formats and by print-on-demand. Some material included with standard print versions of this book may not be included in e-books or in print-on-demand. If this book refers to media such as a CD or DVD that is not included in the version you purchased, you may download this material at http://booksupport.wiley.com. For more information about Wiley products, visit www.wiley.com.
Library of Congress Control Number: 2024933533
ISBN 978-1-394-26321-9 (pbk); ISBN 978-1-394-26323-3 (ebk); ISBN 978-1-394-26322-6 (ebk)
HTML and CSS are awesome technologies, and you can use them to create pages that look amazing. But after you funnel your page to your web server and look at it a few (dozen) times, you may notice a subtle feeling of disappointment creeping in. Why? It can be hard to pin down, but that hint of dismay comes from a stark fact: Your web page just kind of sits there.
Sure, you probably have a link or three to click, but most likely those links just take you to more of your pages that also just kind of sit there. Or maybe a link takes you to another site altogether, one that feels dynamic and alive and interactive. Ah, engagement! Ooh, excitement!
What’s the difference between a page that does nothing and a page that seems to be always dancing? One word: JavaScript. If you want your pages to be dynamic and interactive, you need a bit of behind-the-scenes JavaScript to make it so.
“But,” I hear you object, “HTML isn’t that hard to learn. JavaScript is a programming language, for crying out loud!” I hear you. It’s true that anyone can learn HTML as long as they start with the basic tags, examine lots of examples of how they work, and slowly work their way up to more complex pages. It’s just a matter of creating a solid foundation and then building on it.
I’m convinced that JavaScript can be approached in much the same way. I’m certainly not going to tell you that JavaScript is as easy to learn as HTML. That would be a bald-faced lie. However, I will tell you that there is nothing inherently difficult about JavaScript. I believe that if you begin with the basic syntax and rules, study tons of examples to learn how they work, and then slowly build up to more complex scripts, you can learn JavaScript programming. I predict here and now that by the time you finish this book, you’ll even be a little bit amazed at yourself and at what you can do.
Welcome, then, to JavaScript Essentials For Dummies. This book gives you a solid education on the standard programming language underlying the World Wide Web. You learn how to set up the tools you need and, given any web pages you have (or someone else has) built with HTML and CSS, you learn how to use JavaScript to program those pages. My goal is to show you that adding a sprinkling of JavaScript magic to a page isn’t hard to learn, and that even the greenest rookie programmer can learn how to create dynamic and interactive web pages that will amaze their family and friends (and themselves).
If you’re looking for lots of programming history, computer science theory, and long-winded explanations of concepts, I’m sorry, but you won’t find it here. My philosophy throughout this book comes from Linus Torvalds, the creator of the Linux operating system: “Talk is cheap. Show me the code.” I explain what needs to be explained and then I move on without further ado (or, most of the time, without any ado at all) to examples and scripts that do more to illuminate a concept that any verbose explanations I could muster (and believe me, I can muster verbosity with the best of them).
This book is not a primer on the internet or on using the World Wide Web. This is a book on coding web pages, pure and simple. This means I assume the following:
You know how to operate a basic text editor, and how to get around the operating system and file system on your computer.
You have an internet connection.
You know how to use your web browser.
You know the basics of HTML and CSS.
Yep, that’s it.
This icon points out juicy tidbits that are likely to be repeatedly useful to you — so please don’t forget them.
Think of these icons as the fodder of advice columns. They offer (hopefully) wise advice or a bit more information about a topic under discussion.
Look out! In this book, you see this icon when I’m trying to help you avoid mistakes that can cost you time, money, or embarrassment.
How you approach this book depends on your current level of coding and/or JavaScript expertise (or lack thereof):
If you’ve never programmed before, begin at the beginning with
Chapter 1
and work at your own pace sequentially through
Chapters 2
,
3
,
4
, and
5
. This will give you all the knowledge you need to pick and choose what you want to learn throughout the rest of the book.
If you’ve done some non-JavaScript programming, start with
Chapter 1
, skim through
Chapters 2
through
5
to see how JavaScript does the standard programming tasks, and then pick and choose your topics from there.
If you’ve done some JavaScript coding already, I suggest working quickly through the material in
Chapters 2
through
5
, and then diving into the all-important material on the Document Object Model in
Chapter 6
. From there, you can peruse the rest of the chapters as you see fit.
Chapter 1
IN THIS CHAPTER
Getting a feel for programming in general, and JavaScript in particular
Checking out the tools you need to get coding
Adding comments to your JavaScript code
Storing your code in a separate JavaScript file
In this chapter, you explore some useful JavaScript basics. Don’t worry if you’ve never programmed before. I take you through everything you need to know, step-by-step, nice and easy. As you’re about to find out, it really is fun to program.
Okay, it’s time to roll up your sleeves, crack your knuckles, and start coding. This section describes the standard procedure for constructing and testing a script and takes you through a couple of examples.
The basic container for a script is, naturally enough, the HTML <script> tag and its associated </script> end tag:
<script>JavaScript statements go here</script>
With certain exceptions, it doesn’t matter a great deal where you put your <script> tag. Some people place the tag between the page’s </head> and <body> tags. The HTML standard recommends placing the <script> tag within the page header (that is, between <head> and </head>), so that’s the style I use in this book:
<!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8"> <title>Where do you put the script tag?</title> <script>JavaScript statements go here </script> </head> <body> </body></html>
Here are the exceptions to the put-your-script-anywhere technique:
If your script is designed to write data to the page, the
<script>
tag must be positioned within the page body (that is, between the
<body>
and
</body>
tags) in the exact position where you want the text to appear.
If your script refers to an item on the page (such as a form object), the script must be placed
after
that item.
With many HTML tags, you can add one or more JavaScript statements as attributes directly within the tag.
It’s perfectly acceptable to insert multiple <script> tags within a single page, as long as each one has a corresponding </script> end tag, and as long as you don’t put one <script> block within another one.
You’re now ready to construct and try out your first script. This example shows you the simplest of all JavaScript actions: displaying a basic message to the user. The following code shows the script within an HTML file:
<!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8"> <title>Displaying a Message to the User</title> <script> alert("Hello JavaScript World!"); </script> </head> <body> </body></html>
As shown in here, place the script within the header of a page, save the file, and then open the HTML file within your browser.
This script consists of just a single line:
alert("Hello JavaScript World!");
This is called a statement, and each statement is designed to perform a single JavaScript task. Your scripts will range from simple programs with just a few statements to huge projects consisting of hundreds of statements.
You may be wondering about the semicolon (;) that appears at the end of the statement. Good eye. You use the semicolon to mark the end of each of your JavaScript statements.
In the example, the statement runs the JavaScript alert() method, which displays to the user whatever message is enclosed within the parentheses (which could be a welcome message, an announcement of new features on your site, an advertisement for a promotion, and so on). Figure 1-1 shows the message that appears when you open the file.
FIGURE 1-1: This “alert” message appears when you open the HTML file containing the example script.
How did the browser know to run the JavaScript statement? When a browser processes (parses, in the vernacular) a page, it basically starts at the beginning of the HTML file and works its way down, one line at a time. If it trips over a <script> tag, it knows one or more JavaScript statements are coming, and it automatically executes those statements, in order, as soon as it reads them. The exception is when JavaScript statements are enclosed within a function, which I explain in Chapter 5.
One of the cardinal rules of JavaScript programming is “one statement, one line.” That is, each statement must appear on only a single line, and there should be no more than one statement on each line. I said “should” in the second part of the previous sentence because it is possible to put multiple statements on a single line, as long as you separate each statement with a semicolon (;). There are rare times when it’s necessary to have two or more statements on one line, but you should avoid it for the bulk of your programming because multiple-statement lines are difficult to read and to troubleshoot.
One of JavaScript’s most powerful features is the capability to write text and even HTML tags and CSS rules to the web page on-the-fly. That is, the text (or whatever) gets inserted into the page when a web browser loads the page. What good is that? For one thing, it’s ideal for time-sensitive data. For example, you may want to display the date and time that a web page was last modified so that visitors know how old (or new) the page is. Here’s some code that shows just such a script:
<!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8"> <title>Writing Data to the Page</title> </head> <body> This is a regular line of text.<br> <script> document.write("Last modified: " + document.lastModified) </script> <br>This is another line of regular text. </body></html>
Notice how the script appears within the body of the HTML document, which is necessary whenever you want to write data to the page. Figure 1-2 shows the result.
FIGURE 1-2: When you open the file, the text displays the date and time the file was last modified.
This script makes use of the documentobject, which is a built-in JavaScript construct that refers to whatever HTML file (document) the script resides in (check out Chapter 6 for more about the document object). The document.write() statement tells the browser to insert whatever is within the parentheses to the web page. The document.lastModified portion returns the date and time the file was last changed and saved.
One of the nicest things about HTML and CSS is that the hurdles you have to leap to get started are not only short but few in number. In fact, you really need only two things, both of which are free: a text editor to enter the text, tags, and properties; and a browser to view the results. (You’ll also need a web server to host the finished pages, but the server isn’t necessary when you’re creating the pages.) Yes, there are high-end text editors and fancy graphics programs, but these fall into the “Bells and Whistles” category; you can create perfectly respectable web pages without them.
The basic requirements for JavaScript programming are exactly the same as for HTML: a text editor and a browser. Again, programs are available to help you write and test your scripts, but you don’t need them.
In this book, I make a couple of JavaScript assumptions related to the people who’ll be visiting the pages you post to the web:
Those people have JavaScript enabled in their web browser.