CSS rule sets that select by element type, id, and class
Three elements by type
body {
font-family: Arial, Helvetica, sans-serif;
width: 400px;
margin: lem auto; }
section (
border: 2px solid black;
padding:
p ( margii
jem; )
-25em 0 .25em 3em; )
One element by ID
#first_heading { margin: 0 lem .25em; }
Elements by class
«blue { color: blue; }
tright ( text-align: right; }
The elements displayed in a browser
The Speaker Lineup
October 19: Jeffrey Toobin
November 16; Andrew Ross Sorkin
‘Copyiight SIV Town Hall
Description
© You code a selector forall elements of a specific type by naming the element. This
is referred to as a type selector
© You code an id selector for an element with an id attribute by coding a pound sign
(followed by the id value. This is known as anid selector
© You code a selector for an element with a class attribute by coding a period
followed by the class name. Then, the rule set applies to all elements with that class
name. This is known as a class selector
Figure 1-12 _ How to code the basic CSS selectors28
Section 1 JavaSeript essemtials
How to code CSS rule sets
Figure 1-13 presents the CSS for the Email List application that was pre-
sented earlier in this chapter. This is typical of the CSS for the applications in
this book. Since the focus of this book is on JavaScript and jQuery, not CSS, the
CSS is usually limited, For instance, the CSS in this example doesn’t require id
or class selectors.
Just to make sure we're using the same terminology, this CSS contains seven
rule sets. Each rule set consists of a selector, a set of braces { }, and one or more
rules within the braces. Also, each rule consists of a property name, a colon, the
value or values for the rule, and an ending semicolon.
‘The first rule set in this example applies to the seven HTMLS semantic ele
rents, Itis required for compatibility with older browsers. It tells those browsers
that the semantic elements should be treated as block elements. Without this rule
set, older browsers will treat these elements as inline elements, which is not what
you want.
Although this rule set won't be shown in the CSS for the applications for this
book, itis included with the downloadable applications. As a result, those appli-
cations should run on older browsers.
Beyond that, this book will explain any of the CSS that is relevant to the
JavaScript for an application, So for now, if you know how to code rule sets,
you're ready to continue.Chapter 1 Introduction to web development
The CSS file for a typical application in this book
/* The C88 workaround so the HTMLS semantic ¢:
article, aside, figure, footer, header, nav, section (
display: block;
}
body (
font-family: Arial, Helvetica, sans-serif;
background-color: ‘whites
margin: 0 auto;
width: 650px;
border: 3px solid blue;
}
an ¢
color: blue;
}
section (
padding: 0 2em tem;
}
Label (
oat: lest;
width: idem;
text-align: right;
}
input {
margin-left: lem;
margin-bottom: .Sem;
}
span {(
color: red;
}
Description
‘© Because the focus of this book is JavaScript and jQuery, not CSS, the CSS that’s
used in this book is usually simple. We just apply enough CSS to make each appli-
cation look okay and work correctly.
‘© In fac, for most of the applications in this book, you won't have to understand the
CSS so it won't even be shown. Whenever the CSS is critical to the understanding
of the JavaScript application, though, it will be explained in detail.
Atthe least, you should know that the CSS for an HTML document consists of one
or more rule sets. Each of these rule sets starts with the selector for the rule set
followed by a set of braces { }. Within the braces are one or more rules.
# You should also know that each CSS rule consists of aproperty name, colon, the
value or values for the property, and a semicolon,
Figure 1-13 How to code CSS rule sets.
ments can be formatted */
2930 Section | JavaScript essentials
How to test a JavaScript application
Next, you'll learn how to test a JavaScript application, To do that, you run
the HTML for the web page that uses the JavaScript.
How to run a JavaScript application
‘When you develop a JavaScript application, you're usually working on your
‘own computer or your company’s server, Then, to run the application, you use
one of the four methods shown in figure I-14, Of the four, it’s easiest to run the
HTML page from the IDE that you're using to develop the HTML, CSS, and
JavaScript files. You'll learn more about that ina moment.
In the first of the four methods in this fist list, Fil-9Open File means to
drop down the File mena from the menu bar and select the Open File command.
Similarly, File 9New-Web Project means to drop down the File menu, select
the New command, and then select the Web Project command. This notation is
used throughout this book.
After an application has been uploaded to an Internet server, you can use
the second set of methods in this figure to run the application, The first way is to
enter a Uniform Resource Locator (URL) into the address bar of your browser.
The second way is to click on a link on a web page that requests another page.
You can also use this method iff an application is running on your own computer
or server.
As the diagram in this figure shows, the URL for an Internet page consists of,
four components, In most cases, the protocol is HTTP. If you omit the protocol,
the browser uses HTTP as the default.
‘The second component is thedomain name that identifies the web server
that the HTTP request will be sent to. The web browser uses this name to look
up the address of the web server for the domain, Although you can’t omit the
domain name, you can often omit the “www.” from the domain name.
The third component is the path where the fie resides on the server, The
path lists the folders that contain the file, Forward slashes are used to separate
the names in the path and to represent the server's top-level folder at the start of
the path, In this example, the path is “fourwork/”.
The last component is the name of the file. In this example, the file is named
index.html If you omit the filename, the web server will search for a default doc-
ument in the path. Depending on the web server, this file will be named index.
html, default.htm, or some variation of the two.Chapter 1 Introduction to web development — 34
The web page at c:/jquery/book_apps/ch01/email_list.html
GrEca
Please join our email list
Email Adress:
Re-onter Email Adress:
ist Name
Four ways to run an HTML page that’s on your own server or computer
Use the File Open command with Internet Explorer or the File->Open File
command with Firefox.
© If you're using Windows, find the file in the Windows Explorer and double-click on
it.
Use the features of your text editor or IDE.
Click on a link in the current web page to load the next web page.
‘Two ways to run an HTML page that's on the Internet
# Enter the URL of a web page into the browser's address bar.
Click ona link in the current web page to load the next web page.
The components of an HTTP URL on the Internet
http: //www.modulemedia.com/ourwork/index.html
A Dn
protocol ‘domain name path filename
What happens if you omit parts of a URL
Ifyou omit the protocol, the default of http:// will be used.
Ifyou omit the filename, the default document name for the web server will be
used. This is typically index.html, default.htm, or some variation,
Description
© When you are developing JavaScript applications, you usually store them on your
‘own computer instead of the Internet. So when you test the applications, you run
them from your own computer.
Later, after the applications are deployed to your Internet web server, you can run
the applications from the Internet.
Figure 1-14 How to run a JavaScript application32 Section 1 JavaSeript essemtials
How to ensure cross-browser compatibility
If you want your web site to be used by as many visitors as possible, you
need to make sure that your web pages are compatible with as many browsers as
possible, That's known as cross-browser compatibility. That means you should
test your applications on as many browsers as possible, including the five
browsers summarized in figure 1-15, as well as the older versions of those
browsers.
‘The table in this figure shows the current release numbers of these browsers
and their rating for HTMLS support. To get an updated version of this informa-
tion, though, you can go to the web site at . This web site
will also rate the browser that you're using when you access it.
In general, Internet Explorer (IE) gives web developers the most problems
because it’s the least standard. In contrast, the other four browsers generally
support the same features so if a web page runs on one of them, it will also run
on the others, The other four browsers also provide for automatic updates, but IE
typically hasn't done that, As a result, the other four browsers are most likely to
support the latest features of HTMLS and CSS3.
Incidentally, IE not only has some HTML and CSS incompatibilities, but
also some JavaScript incompatibilites. In fact, one of the benefits of using
{Query is that its functions have already been tested for cross-browser compat
ibility, As a result, they will work on all browsers.
To provide for browsers that don’t support the HTMLS and CSS3 features
that are presented in this book, you need to use the workarounds shown in this
figure, However, its difficult to test your web pages in older browsers because
(1) you can’t get them anymore and (2) you can’t put all versions of the old
browsers on one system even if you could get them.
If you're a student, you probably won't need to test your web pages on old
browsers. But for production applications, that type of testing is essential. To
help you do it, you can search the Internet for web sites or software products that
provide ways to test your pages on old browsers.
To do the exercises in this book, you can get by with just the current ver
sions of IE and Firefox. But if you're using a Mac OS system, you won't be able
to install IE so you can skip any steps that require it or substitute Safari for IE
references. For a production system, of course, you need to install all five brows-
ers and make sure your web pages work on all of them.Chapter 1 Introduction to web development 38
The current browsers and their HTMLS ratings (perfect score is 500)
Browser ee)
Google Chrome
Opera
Movilla Firefox
Apple Safari
Internet Explorer
The web site for these ratings
Guidelines for cross-browser compatibility
Test your web pages on all of the major browsers, including all of the older versions
of these browsers that are still commonly used.
Use the HTMLS and CSS3 features that are supported by all of the modern brows-
ers, which are the features that are presented in this book. But use the workarounds.
so these applications will run on the older browsers too.
The two workarounds for using the HTMLS5 semantic elements
The JavaScript shiv that lets older browsers know about the elements
The CSS rule set that sets the semantic elements to block elements
article, aside, figure, figcaption, footer, header, nav, section (
display: block; }
How to test your web pages in older browsers
‘© One of the problems in cross-browser testing is that you can't install all of the old
browsers on one system. In particular, Windows doesn’t let you install more than
one version of IE at the same time.
The solution is to use programs or web sites that offer this type of testing. To find out
what's available, try searching for “browser testing software” or “cross browser testing”.
Description
© Today, there are still differences in the way that different browsers handle HTML,
CSS, and JavaScript. As a developer, though, you want your web pages to work on
as many different web browsers as possible, This is referred to as cross-browser
compatibility.
© One of the benefits of using jQuery is that it provides cross-browser compatibility
for the JavaScript that it provides. However, the HTML, CSS, and other JavaScript
can still cause compatibility problems.
‘In general, Internet Explorer gives web developers the most problems because it is,
the least standard and hasn't provided for automatic updates.
Eventually, all browsers will support HTMLS and C883 so the workarounds won't
be necessary.
Figure 1-15 How to ensure cross-browser compatibility34 Section | JavaScript essemtals
How to use Aptana
to develop JavaScript applications
Because HTML, CSS, and JavaScript are just text, you can use any text edi
tor to create the files fora JavaScript application, However, a better editor or an
Integrated Development Environment (IDE) can speed development time and
reduce coding errors. That's why we recommend Aptana Studio 3. It isa free
IDE that runs on Windows, Mac OS, and Linux, and it can greatly improve your
productivity.
In the appendix for this book, you can learn how to install Aptana, You can
also learn how to use Aptana for the common development functions in the top-
ics that follow. If you prefer to use another editor, of course, you can skip these
topics. But even then, you may want to browse these topics because they will
give you a good idea of what an IDE should be able to do. They may also encour
age you to give Aptana a try.
How to create a project
In Aptana, a prcject consists of the folders and files for a complete web
application, Once you create a project, i's easier to work with its folders and
files, to create new files for the project, and so forth.
To create a project, you use the procedure in figure 1-16. The result of this
procedure is that you end up with a named project that starts with the top-level
folder for the application. Then, you can easily access the folders and files for the
application by using the App Explorer window that’s shown in the next figure.
To make it easier to work with the applications for this book, we recommend
that you create an Aptana project that includes all of them. To do that, you can
create a project named jQuery Book Apps that starts with the path shown in this
figure. The final dialog box for doing this is displayed in this figure.Chapter 1 Introduction to web development
The last dialog box for creating an Aptana project
Bia
2 EBOum0- BE%-0- l4~
(ReAppeplors Ei] Pajecttioe| GY 5)
See cene ner pe
Prpctnme suey pe
Lectin Soe
AN hese sherri eC eer
[ene cn an a ee a9 he ee are
The folder that contains the folders for all of the book applications
c:\murach\jquery\book_apps
How to create a project
© Use the File 3New-9Web Project command to display the New Web Project dialog
box that’s shown above. Or, in the App Explorer window, click on the Create
Project button, select Web Project in the dialog box that’s displayed, and click the
Next button to display the New Web Project dialog box.
Inthe New Web Project dialog box, enter a name for the project. Next, uncheck
the Use Default Location box, click on the Browse button, and select the top-level
folder for the project.
«Read the warning message that appears so you realize that deleting the project in
‘Aptana may also delete the project on the disk drive. Then, click the Finish button.
Description
‘© Aptana works the best when you set up projects for the web applications that you're
developing and maintaining.
© Ingeneral, each Aptana prc ect should contain the folders and files for one web
application. For the purposes of this book, however, you can set up one project for
all of the book applications, one project forall of the exercises, and one project for
all of the exercise solutions.
Figure 116 How to create a project in Aptana36 Section 1 JavaSeript essemtials
How to open or close an HTML, CSS,
or JavaScript file
Figure 1-17 shows how to open or close an HTML, CSS, or JavaScript file
after you've created a project. Here, the jQuery Book Apps project is shown in
the App Explorer window on the let side of Aptana, If you have created more
than one project, you can switch from one to another by using the drop-down
project list that’s at the top of the App Explorer window.
Once you have the correct project open, you can drill down to the file that
‘you want to open by clicking on the plus signs for the folders. In this example,
the ch0l and email_list folders have been expanded so you can see the four files
for the Email List application. Then, to open a file, you just double-click on it.
‘When you open file in Aptana, itis opened in a new tab. This means that
you can have several files open at the same time and move from one to another
bby clicking on a tab. This makes it easy to switch back and forth between the
HTML, CSS, and JavaScript files for a web page. This also makes it easy to copy
code from one file to another.
If you want to open a file that isn't part of a project, you can do that by using
one of the methods shown in this figure, First, you can use the Project Explorer
‘window to locate the file on your computer and then double-click on it. Second,
you can use the File->Open File command to open a file.
To close one or more files, you can use one of the three methods shown in
this figure, This makes it easy to close all of the files except the ones that you're
currently working with, And that helps you avoid the mistake of making a
change to the wrong file.
As you work with Aptana, you'll see that it has the same type of interface
that you've used with other programs. So if you want to do something that isn't
presented in this chapter, try right-clicking on an item to see what menu options
are available. Check out the other buttons in the toolbar. See what's available.
from the drop-down menus, With a little experimentation, you'll find that this
program is not only powerful, but also easy to use.Chapter 1 Introduction to web development 37.
Aptana with the App Explorer shown and a JavaScript file
in the second tab
[Ewe Bok pps Olena lami atom ud
tc sete ape ieee
BEO- SaS-O- M\¥- SE owe)
ee.
(ermten. o[Sretn|=O |e lama] =5
GMs >> | Dar Stanton (a) :
Ei 2 Te eturm caret grtlenentsI4(i0);,
{Oey Books =
thar Jouniise = function ((
areal ladaresst > $¢
sae T
& ar eraladares
5 ar fevalld = tres
yaret
Binns
Boer
Boa P
Oine % [eB Ssmpls| He = =
yeti tee
| adress? error") firetChild.nedeale
8 @ onus
rave"). <=“) ¢
aero) Flrstehik.ndevelue = “his fielé
valid = false, 2
How to open a file within a project
¢ Use the drop-down list in Aptana’s App Explorer to select the project.
© Then, locate the file in the App Explorer and double-click on it.
‘Two ways to open an HTML file that isn’t in a project
Use the Project Explorer to locate the file, and double-click on it.
Use the File Open File command.
How to close one or more files
© To close one file, click on the X in the tab for the file.
# To close all of the files except one, rightclick on the tab you don’t want to close and
select Close Others.
© To close all of the files, right click on any tab and select Close All.
Description
‘¢ When you open a file, the file is displayed in a new tab.
Figure 1-17 How to open or close an HTML, CSS, or JavaScript file in Aptana38 Section | JavaScript essentials
How to change the colors
that highlight the syntax
‘When you opena file in Aptana, one of the first things you might want to do
is change the colors that are used to highlight the syntax of HTML, CSS, and
JavaScript code, That’s because the default settings are light colors on a dark
background that can be hard to read.
To change the colors, you can use the procedure in figure 1-18, In this book,
we use the Dreamweaver theme, but you can experiment with other themes until
you find one that you like. If you click the Apply button after you select a theme,
you can see the colors that are used in the window behind the dialog box. Then,
if you like the colors, you can click the OK button to close the dialog box.Chapter 1 Introduction to web development —— 39
Aptana’s Themes dialog box
‘ypefita tet ‘Themes Or ory
Genet
plana Sto
comm (Geammsnstscas) (2) fers) [inven [pen]
a :
Ferma Epes Lire :
aseret eb ne ne ohh (a)
= tering
Ts bie E
ns Mac Classic jw 2
Gama Mee
Tene ee alata
2 Pastels on Dark a Ii)
Vataason em Z cy
Web Sevee E
Ravowe fF
- fe
reaps
= ie
Rrvbeon
Toon = fam ~
=
itoplt tinen stud) views
App taal on St) eon
top estaronto view
Procedure
Use the Window Preferences command to open the Preferences dialog box.
Click on Aptana Studio, and then click on Themes to display the Themes dialog
box.
© Choose a theme from the drop-down list.
Description
‘© Aptana displays different parts of the JavaScript statement in different colors so the
statements are easier to interpret.
Ifyou don’t like the colors that are used, you can change the colors by using the
procedure above.
Figure 1-18 How to change the colors that highlight the syntax in Aptana40
Section 1 JavaSeript essemtials
How to edit a file
Figure 1-19 shows how to edit a JavaScript file with Aptana, but editing
‘works the same for HTML and CSS files. When you open a file with an html,
css, or js extension, Aptana knows what type of file you're working with so it ean
use color to highlight the syntax components, The good news is that color coding
is also used for CSS that’s ina style element of an HTML document or
JavaScript that’s in a script element of an HTML document.
As you entera new line of code, the auto-completion feature presents lists of
‘words that start with the letters that you've entered. This type of list is illustrated
by this figure. Here, the list shows the JavaScript choices after the letter r has
been entered, Then, you can select a word and press the Tab key to insert it into
your code.
This also works with HTML and CSS entries. If, for example, you type Open File command
to open this HTML file:
¢:\murach\jquery\book_apps\ch0l\email_list\index.html
To test what happens when you don’t enter any data, just click the Join our L
button without entering any data, Then, you can see the error messages that
are displayed.
3. _Enteran email address in the first text box and invalid data in the second
text box and click the Join our List button to see what error messages are
displayed.
4. Enter valid data for all three text boxes and click on the button. Then, the data
is submitted for processing and a new web page is displayed.
Exercise 1-2 Run other section 1 applications
This exercise has you run the applications presented in chapter 6, These
applications will give you some idea of what you'll able to do when you
complete this section.
Open this file in the Firefox browser:
¢:\murach\jquery\book_apps\ch06\faqs_links\index.html
Then, click on one of the headings to display the text for it, and click the
heading again to hide the text.
6. Open this file in the Firefox browser:
¢:\murach\jquery\book_apps\ch06\image_swap\index.html
‘Then, click on the small images to see the large image get swapped.
7. Open this file in the Firefox browser:
¢:\murach\jquery\book_apps\ch06\slide_show\index.html
Watch the slide show.Chapter 1 Introduction to web development
Exercise 1-3 Get started with Aptana
This exercise is for readers who are going to use Aptana with this book. It
guides you through the process of creating projects that provide easy access to
the book applications and exercises that you've downloaded.
Create the projects
1. Start Aptana, and use the procedure in figure 1-16 to create a project for the
book applications that are stored in this folder:
¢:\murach\jquery\book_apps
This project should be named jQuery Book Apps, and the entries for the last
dialog box should be just like those in this figure.
2. Use the same procedure to create a project named jQuery Exercises for the
exercises that are stored in this folder:
cr\Jquery\exercises
as well as a project named jQuery Solutions for the exercise solutions that are
stored in this folder:
#\murach\jquery\solutions
‘Test the Email List application
3. Use the drop-down list in the App Explorer to select the jQuery Exercises
project. This provides access to all of the exercises that are inthis book.
4. Click on the plus sign before ch01 to display the email_list folder, and click
on the plus sign for the email_list folder to display the files for the Email List
application.
5. Double-click on the file named index.htm! to open that file, Then, click the
Run button in the toolbar to run the application in the default browser. That
will automatically switch you to that browser.
6. Switch back to Aptana, and click on the down arrow to the right of the Run
button, Ifthe drop-down list offers Internet Explorer, click on it to run the
application in that browser. Then, return to Aptana.
Edit the JavaScript code
7. Inthe App Explorer, double click on the file named email_li
file, and note the colors that are used for syntax highlighting,
8. If you don’t like the colors that are used, use the procedure in figure 1-18 to
change them.
js to open that
9. Inthe JavaScript file, delete the right parenthesis in the first line of code. This
should display two error markers. Then, hover the mouse over the markers to
display the error descriptions. This illustrates Aptana’s error-checking feature.
Now, undo the change that you made. (To undo a change with the keyboard,
press Ctrl+Z.)
4748
Section 1 JavaSeript essemtials
10.
lL.
12.
13.
In the JavaScript file, after the third statement that starts with var, start a
‘statement on a new line with these characters:
if (e
This should display alist of the possible entries that start with the letter e.
Here, you can see that email Address| and emailAddress? are included in the
list. These are the variables that are created by the first two var statements,
and this illustrates Aptana's code-completion feature, Now, undo this change.
Enter this statement on a new line that comes right before the last Line of the
JavaScript code, which consists of justa right brace (}):
alert("The DOM has now been built");
In other words, this statement will become the second last line in the file.
To test the statement that you've added, click on the Save All button in the
toolbar to save your changes. Then, switch to your browser and click on the
Reload or Refresh button to run the application with this change. This should
display a dialog box that you can close by clicking on its OK button, After
that, the application should work the same as it did before.
If you're curious, do more experimenting on your own, Then, close the files
and exit from Aptana,Getting started
with JavaScript
‘The goal of this chapter is to get you off to a good start with JavaScript,
especially if you're new to programming. If you have programming experience
with another language, you should be able to move rapidly through this chapter.
Otherwise, take it easy and do the exercises at the end of this chapter.
How to include JavaScript in an HTML document.
‘Two ways to include JavaScript inthe head of an HTML document.
How to include JavaScript in the body of an HTML document.
How to create identifiers.
How to use comments.
How to use objects, methods, and properties.
How to work with JevaSeript date.
‘The primitive datatypes.
How to code numeric expressions nn
How to work with numeric variables. nnn
How to work with string and Boolean Variable in
How to use the parselnt and parseFloat methods.
How to code control statements..
How to code conditional expressions.
How to code if statements.
How to code while and do-while loops.
How to code for loops.
‘Two illustrative applications.
‘The Miles Per Gallon application.
‘The Test Scores application,
How to find errors in your code.
How to get ertor messages with Firefox.50
Section 1 JavaSeript essemtials
How to include JavaScript
in an HTML document
In chapter 1, you saw how the JavaScript for an application can be coded in a
separate file, But there are actually three different ways to include JavaScript in
an HTML document. You'll learn all three now.
Two ways to include JavaScript
in the head of an HTML document
Figure 2-1 presents two of the three ways to include JavaScript in an HTML
document. As you saw in the last chapter, one way is to code the JavaScript in a
separate external fle. Then, you code a script element in the head section of the
HTML document to include that file.
In the script element, the sre attribute is used to refer to the external file. For
this element, you can also code a type attribute with the value “text/javascript”
to tell the browser what kind of content the file contains. But with HTMLS, that
attribute is no longer needed because the assumption is that all files that are
referred to in script elements contain JavaScript.
In the example in ths figure, the stc attribute refers toa file named caleu-
Jate_mpgjs. The assumption here is that this fie is inthe same folder as the
HTML file. Otherwise, you need to code a relative URL that provides the right
path for the file. If, for example, the JavaScript file is in a folder named javascript
and that folder is in the same folder as the HTML file, the sre attribute would be
coded this way:
This works the same as it does for any other file reference in an HTML
document.
The second way to include JavaScript in an HTML document is to code the
JavaScript within the script element in the head section, This can be referred to
as embedded JavaScript. Note, however, that the application will work the same
whether the JavaScript is embedded in the head section or loaded into the head
section from an external file.
The benefit of using an external file is that it separates the JavaScript from
the HTML. The benefit of using embedded JavaScript is that you don't have to
switch between the HTML and JavaScript files as you develop the application, In
the examples in this book, you'll see both uses of JavaScript.Chapter? Getting started with JavaScript 51
‘Two attributes of the script element
CESS
Specifies the location and name of an external JavaScript file.
With HTMLS, this attribute can be omitted. If you code it,
use “text/javascript” for JavaScript code.
A script element in the head section that loads an external JavaScript file
A script element that embeds JavaScript in the head section
ad>
Description
© A script element in the head section of an HTML document is commonly used to
identify an external JavaScript file that should be included with the page.
A script element in the head section can also contain the JavaScript statements that
are included with the page. This can be referred to as embedded JavaScript.
* Ifyou code more than one script element in the head section, the JavaScript is
included in the sequence in which the script statements appear.
‘© When a script element in the head section includes an external JavaScript fle, the
JavaScript in the file runs as if it were coded in the script element.
Figure 2-1 Two ways to include JavaScript in the head of an HTML documentSection 1 JavaSeript essemtials
How to include JavaScript
in the body of an HTML document
Figure 22 shows a third way to include JavaScript in an HTML document.
This time, the two script elements in the first example are coded in the body of.
the HTML document. When a script element is coded in the body, the element is
replaced by the output of the JavaScript code when the application is loaded.
If you want to provide for browsers that don't have JavaScript enabled, you
can code a noscript element after a script element as shown in the second exam
ple. Then, if JavaScript is disabled, the content of the noscript element will be
displayed. But if JavaScript is enabled, the script element is replaced by the out-
put of the JavaScript code and the noscript element is ignored. This way, some
output will be displayed whether or not JavaScript is enabled.
In the second example, the noscript element is coded right after a script
element, so 2012 will replace the output ofthe script element if JavaScript isn’t
enabled in the browser, This means that the result will be the same in the year
2012 whether or not JavaScript is enabled, But in the year 2013, the year will be
updated by the JavaScript if it is enabled.
You can also code a noscript element that doesn’t follow a script element, For
instance, you can code a noscript element atthe top of a page that warns the user
that the page won't work right if JavaScript is disabled. This is illustrated by the
third example, In this case, nothing is displayed if JavaScript is enabled and the
message is displayed if JavaScript is disabled.
Inail of the applications in this book, the JavaScript is either embedded in
the head section of the HTML or in an external fie that’s identified in the head
section of the HTML. However, you shouldn't have any trouble including the
JavaScript in the body of an HTML document whenever you want to do that.Chapter? Gening started with JavaSeripn 5B
JavaScript in the body of an HTML document
©senbsp; » San Joaquin Valley Town Hall
The result of the JavaScript in a web browser Current date: Mon Mar 12 2012 © 2012, San Joaquin Valley Town Hall” A noscript element in the body of an HTML document
kcopysénbsp; » San Joaquin Valley Town Hall
A noscript element at the start of an HTML document
Description
© Ifa script element is coded in the body of a document, it is replaced by the output
of the JavaScript code.
© The noscript element can be used to display content when JavaScript is disabled in
a user's browser.
Figure 22 Howto include JavaScript in the body of an HTML document54 Section | JavaScript essentials
The JavaScript syntax
The syntaxof JavaScript refers to the rules that you must follow as you code
statements. If you don't adhere to these rules, your web browser won't be able to
interpret and execute your statements.
How to code JavaScript statements
Figure 2-3 summarizes the rules for coding JavaScript statements. The first
rule is that JavaScript is case-sensitive. This means that uppercase and lower-
case letters are treated as different letters, For example, the names salestax and
salesTax are treated as different words.
The second rule is that JavaScript statements must end with a semicolon. If
you don’t end each statement with a semicolon, JavaScript won't be able to tell
where one statement ends and the next one begins.
‘The third rule is that JavaScript ignores extra whitespace in statements.
Since whitespace includes spaces, tabs, and new line characters, this lets you
break long statements into multiple lines so they're easier to read.
Be careful, though, to follow the guidelines in this figure about where to
splita statement. If you don‘ spit a statement at a good spot, JavaScript will
sometimes try to help you out by adding a semicolon for you, and that can lead
to errors.Getting started with JavaScript 55
A block of JavaScript code
var jointist = function () (
var emailAddressi = §("email_addressi").value;
var emailaddress? = §("email_address2") value
if (enailaddressi r¢
alert ("Email Address is required.");
) else if (emailaddress2 == **) (
alert ("Second Email Address is required.");
if (emailaddressi !== emailaddress2) (
alert ("Second Email entry must equal first entry.
) else if (S(*first_name").value == "") (
alert ("First Name is required.");
) else ¢
$("email_form"). submit ();
del
d
?
The basic syntax rules
# JavaScript is case-sensitive.
© JavaScript ignores extra whitespace within statements.
© Each JavaScript statement ends with a semicolon.
How to split a statement over two or more lines
© Splita statement after:
~ anarithmetic or relational operator such as +, -%/
= an opening brace ( { ), bracket ([), or parenthesis
= aclosing brace ( } )
>,or<
© Do not split a statement after:
~ an identifier, a value, or the return keyword
= aclosing bracket (] ) or parenthesis
Description
© A JavaScript statement has a syntax that’s similar to the syntax of Java.
© Whitespace refers to the spaces, tab characters, and return characters in the code,
and it is ignored by the compiler. As a result, you can use spaces, tab characters,
and return characters to format your code so its easier to read.
© Insome cases, JavaScript will try to correct what it thinks is a missing semicolon
by adding a semicolon at the end of a split line. To prevent this, follow the guide
lines above for spitting a statement,
Figure 2-3 How to code JavaScript statements56 Section 1 JavaSeript essemtials
How to create identifiers
Variables, functions, objects, properties, methods, and events must all have
names so you can refer to them in your JavaScript code, An identifiers the name
given to one of these components.
Figure 2-4 shows the rules for creating identifiers in JavaScript. Besides the
first four rules, you can't use any of the JavaScript reserved words (also known
as keywords) as an identifier. These are words that are reserved for use within
the JavaScript language, You should also avoid using any of the JavaScript global
properties or methods as identifiers, which you'll learn more about as you prog-
ress through this book.
Besides the rules, you should give your identifiers meaningful names.
‘That means that it should be easy to tell what an identifier refers to and easy to
remember how to spell the name, To create names like that, you should avoid
abbreviations. If, for example, you abbreviate the name for monthly investment
‘as mon_iny, it will be hard to tell what it refers to and hard to remember how
you spelled it, Bu if you spell it out as monthly_ investment, both problems are
solved.
Similarly, you should avoid abbreviations that are specific to one industry
or field of study unless you are sure the abbreviation will be widely understood.
For example, mpg is a common abbreviation for miles per gallon, but cpm could
stand for a number of different things and should be spelled out.
To create an identifier that has more than one word in it, many JavaScript
programmers use a convention called camel casing With this convention, the
first letter of each word is uppercase except for the first word, For example,
monthlyinvestment and taxRate are identifiers that use camel casing.
The alternative is to use underscore characters to separate the words in an
identifier, For example, monthly_ investment and tax_rate use this convention. If
the standards in your shop specify one of these conventions, by all means use it
Otherwise, you can use whichever convention you prefer..but be consistent.
In this book, we use underscore notation for the ids and class names in the
HTML and camel casing for all JavaScript identifier. That way, it will be easier
for you to tell where the names originated.You might also like