gf-cpe06-midterm-transes-backup
gf-cpe06-midterm-transes-backup
ONLINE TECHNOLOGIES • You use JavaScript to make the pages come alive,
with auto-populating form fields, and all kinds of bells
and whistles that enhance the user experience.
BOOK III: JAVASCRIPT • One of the most common things that we hear from
I. CHAPTER 1: Understanding JavaScript Basics nontechnical folks is confusing or calling JavaScript,
II. CHAPTER 2: Building a JavaScript Program “Java.”
III. CHAPTER 3: Adding jQuery
IV. CHAPTER 4: Reacting to Events with JavaScript and jQuery
o Now that you know that the two are
V. CHAPTER 5: Troubleshooting JavaScript Programs completely different, you won’t do the same!
o You will, however, need to resist the urge to
REFERENCE correct people when you hear them confuse
the two languages.
Module
TECHNICAL STUFF
CHAPTER 1: UNDERSTANDING JAVASCRIPT BASICS • JavaScript is defined by the specification known as
In This Chapter ECMA-262.
✓ Understanding JavaScript’s role in web programming o ECMA - European Computer Manufacturers
✓ Adding JavaScript to a page Association
• Web browsers have varying degrees of support for the
• This minibook is all about JavaScript and its place in ECMA-262 specification, so the exact version of
building web applications. JavaScript that’s available in the browser varies
• JavaScript is a very powerful language, and you can according to the version of the browser being used.
use it to add great features to enhance the user
experience. KNOWING WHAT JAVASCRIPT CAN DO
• In this chapter, we tell you a little bit about the types of • JavaScript is an integral part of web pages today.
interactivities that you can add to a web page with o When you see something like Google Maps,
JavaScript and then show you how to add JavaScript where you can scroll left and right by
to a page. simply dragging the map, that’s JavaScript
• In the next chapter, we show you how to use JavaScript behind the scenes.
to perform some very basic programming functions, o When you go to a site to look up flight details,
and then we follow that with a look at more practical and the site automatically suggests
items with JavaScript. airports as you type into the field, that’s
JavaScript.
VIEWING THE WORLD OF JAVASCRIPT o Countless widgets and usability
• JavaScript is used for web programming to enhance enhancements that you take for granted
or add to the user experience when using a web when you use the web are actually JavaScript
page. programs.
• This section looks at some of the aspects of JavaScript • JavaScript programs run in the user’s web browser.
that will help you understand the language and give o This is both a blessing and a curse.
you a good foundation upon which you’ll be able to • On the one hand, by running on the user’s web
really make your web pages stand out. browser it means that your server doesn’t need to
JavaScript isn’t Java run the program.
• On the other hand, by running in the user’s browser it
• Don’t be confused by the name.
means that your program runs slightly differently
o JavaScript has absolutely nothing to do
depending on the version of browser that the user
with Java — the coffee or the programming
is using on your site.
language.
o In fact, the user may have JavaScript turned
• JavaScript’s name came about because marketing
off completely!
folks wanted to latch onto the “cool” factor back
• While theoretically all JavaScript should run the
when the Java programming language was shiny and
same, in practice it doesn’t.
new.
• Internet Explorer, especially older versions like 6 and
• Java is a heavy language that doesn’t necessarily
7, interpret JavaScript in entirely different ways than
run on everyone’s computer;
other browsers like Firefox and Chrome.
o people have to install extra software to get
o This means that you need to create two
it to run.
different programs or two different ways to
o Although powerful, Java is not meant for the
make the same thing work on your web
types of web programming that you usually
pages.
need to do.
o Luckily, there are ways around this, which you
• JavaScript, on the other hand, is included with just
discover in this minibook.
about every web browser and doesn’t need
anything else installed.
jtmh & jeanni
EXAMINING THE WAYS TO ADD JAVASCRIPT TO A PAGE • Although that method works for small scripts and
• Although JavaScript is included in everyone’s web certainly comes in handy for showing examples in this
browser, you still need to program the actions that book, a better way to add JavaScript is by using
you want to happen on your page. external JavaScript files.
• You might recall from Book II, Chapter 2, if you’ve
TIP
read it, that you can style your page with Cascading
Style Sheets (CSS) added directly to the HTML or • Using external JavaScript files is the same concept
reference a separate CSS file. as using external files for CSS.
o Similarly, this section shows the various ways o Doing so promotes reusability and makes
to incorporate JavaScript into a page. troubleshooting and changes easier.
• You can: • You can add external JavaScript by using the src
o add the JavaScript directly to the HTML file, attribute, like this:
o reference a separate JavaScript file, <script type=”text/javascript”
o or do both — and we help you understand src=”externalfile.js”>
when each option is appropriate. </script>
ADDING THE JAVASCRIPT TAG • This example loads the file “externalfile.js” from the
• You add JavaScript to a page with the <script> tag, same directory on the web server.
like this: • The contents of that file are expected to be
<script type=”text/javascript”> JavaScript.
// JavaScript goes here REMEMBER
</script>
• Notice in this example that there’s nothing between
• You may see various ways to include JavaScript in a the opening <script> and closing </script> tags.
page, like “text/ecmascript” or without the type • When using an external JavaScript file, you can’t put
attribute at all, just an empty <script> tag. JavaScript within that same set of tags.
• These methods work, sort of, and some of them are • You could add a reference, like the one shown,
technically correct. anywhere in the page, but the traditional spot for
• But the one that you see most often and the one that that is in the <head> section of the page.
we’ve had the best luck with is the one shown, with a • Also note there’s nothing preventing you from using an
type of “text/javascript”. external JavaScript file along with in-page JavaScript,
• If you’re wondering, the sets of double slashes you so this is perfectly valid:
see in this example start a comment, which we tell • This example loads an external JavaScript file and
you more about in the next chapter. then runs some JavaScript right within the page.
ADDING JAVASCRIPT TO A PAGE’S HTML <!doctype html>
• Always position the JavaScript code after the opening <html>
<script type=”text/javascript”> tag and
before the closing </script> tag. <head>
<title>Another Basic Page</title>
• You can include those tags in both the <head> section
<script type=”text/javascript”
and the <body> section of a page. src=”externalfile.js”>
• You could actually place as many of those separate </script>
script elements as you want on a page but there’s
usually no reason to do so. <script type=”text/javascript”>
Here’s an example showing JavaScript in two different locations // JavaScript goes here
in a page: </script>
<!doctype html> </head>
<html>
<body>
<head> <h1>Here’s another basic page</h1>
<title>Another Basic Page</title> </body>
<script type=”text/javascript”> </html>
// JavaScript goes here
</script> CHAPTER 2: BUILDING A JAVASCRIPT PROGRAM
</head> In This Chapter
✓ Understanding the basic syntax of JavaScript
<body> ✓ Implementing JavaScript functions
<h1>Here’s another basic page</h1> ✓ Working with JavaScript and HTML
<script type=”text/javascript”> ✓ Using JavaScript with a web browser
// JavaScript can also go here
</script> • The preceding chapter shows how to add the
</body> JavaScript tag to a page, and this chapter
</html> concentrates on what you can do after that.
USING EXTERNAL JAVASCRIPT • Key to understanding a programming language is
learning its syntax.
• The example you just saw shows JavaScript within
the page, in much the same way that you can add • Just like when you learn a foreign language and you
CSS inside of a page. need to learn the words and grammar of the language,
the syntax of a programming language is just that:
• JavaScript variables can hold strings, which are • Save the file as string.html in your document root.
essentially words enclosed in quotes, or numbers, • Open your browser and view the page by going to
like you saw in the example. http://localhost/string.html. You should see an alert
like the one in Figure 2-3.
REMEMBER
• Variables need to be named in a certain way.
• Variables need to
o begin with a letter and
o can’t begin with a number.
• Though certain special characters are fine, in general
variables should contain only letters and numbers.
Variable names should be descriptive of what they
contain or what they do.
HOLDING MULTIPLE VALUES IN AN ARRAY • Look closely at Figure 2-3. Notice that there’s no space
• Variables hold one thing and they do it well, but there between the words Partly and Cloudy.
are times when you want to hold multiple things. • In order to have a space there it needs to be added
• Sure, you could just create multiple variables, one for either on the end of the word Partly or at the beginning
each thing. of the word Cloudy.
• You could also create an array.
o An array is a special type of variable used WORKING WITH NUMBERS
to hold multiple values. •You already saw that JavaScript variables can hold
• Here’s an example: numbers.
var myArray = [“Steve”,”Jakob”,”Rebecca”,”Owen”]; • You can also do math with JavaScript, either
o directly on the numbers
• This array contains four things, known as elements. o or through variables.
You see more about arrays later, when we tell you • For example, adding two numbers:
about loops. var myNumber = 4 + 4;
PERFORMING ACTIONS MULTIPLE TIMES WITH LOOPS • Now take a look at how to determine the length of an
• Sometimes you want to repeat the same code over array. Earlier in the chapter you saw an array like this
and over again. This is called looping. one:
• JavaScript includes a couple ways to do it, including for var myArray = [“Steve”,”Jakob”,”Rebecca”,”Owen”];
and while.
• A common use of a for loop is to spin through an array
For what it’s worth and do something with each value.
• If you want to do something multiple times in • The conditional in the example for loop you saw earlier
JavaScript, a common way to do it is with a for loop. set the value at 10.
• A for loop has pretty specific syntax, as you see here: • But how do you know how many values are in an
for (var i = 0; i < 10; i++) { array?
// Do something here • Yes, you easily could count the number of variables in
} the array shown, but sometimes you have no idea how
many elements are in an array.
• That structure includes three specific things within the • You can ask the array itself to tell you how long it is by
parentheses. asking it.
• Variable: First, a variable is set up, in this case simply • You ask through the length property, like this:
called i. That variable is set to the number 0.
• Condition: Next is the condition to be tested. In this myArray.length;
case, the loop tests whether the variable i is less
• Listing 2-2 shows an example that loops through the
than 10. If i is less than 10, the code inside the braces
array shown and displays each element.
runs.
Listing 2-2: Using a for Loop on an Array • You’ve been using one throughout the chapter:
<!doctype html> alert().
<html> o The alert() function creates a dialog in
<head> the browser.
<title>JavaScript Chapter 2</title>
</head> CREATING FUNCTIONS
<body> • Functions are created with the:
<h1>Here’s another basic page</h1> o function keyword
<script type=”text/javascript”> o followed by the name of the function,
var myArray = [“Steve”,”Jakob”,”Rebecca”,”Owen”]; o parentheses, and
for (i = 0; i < myArray.length; i++) {
alert(“Hello “ + myArray[i]);
o opening and closing braces, like this:
} function myFunction() {
</script> // Function code goes here
</body> }
</html>
• What you do inside of the function is up to you.
• This code uses a standard for loop but instead of
• Anything that you can do outside of the function you
setting the length to a certain number, it uses the length
can do inside of it.
property to find out how long myArray really is.
• If you find that your page needs to update a bunch of
• Each time through the loop, an alert is shown, like the HTML, you could use a function so that you don’t
one in Figure 2-8. need to keep repeating that same code over and
over again.
ADDING FUNCTION ARGUMENTS
• The power of functions comes with their capability to
accept input, called arguments, and then do
something with that input.
• For example, here’s a simple function to add two
numbers:
• The i variable is used right within the loop, to access function addNumbers(num1,num2) {
each element of the myArray variable. alert(num1+num2);
• You see, an array is an ordered list of things, with the }
order being provided by numbers that you don’t
normally see. These hidden numbers are called • This function accepts two arguments called num1
indexes. The index of the first element in an array is 0 and num2.
(not 1 as you might expect). o Those arguments are then used within the
• In this example, since i is 0 the first time through the alert() function.
loop it can access the first element. o You’ve seen the alert() function
• The second time through the loop, as shown in Figure throughout the chapter and now you
2-8, i is equal to 1 and so the second element is shown. understand a bit more about what’s going on!
• The alert() function accepts one argument, the
TIP text to display in the alert dialog.
• The syntax that you see there, myArray[i], is a really • In this case, because you’re adding two numbers the
common syntax that you see in for loops. alert displays the resulting number.
While you’re here • You work through an exercise for this in the following
section.
• Another type of loop is called a while loop, and it looks
like this: CALLING A FUNCTION
while (i < 10) { • Just creating the function isn’t enough;
// Do something interesting o you need to call it too.
// Don’t forget to increment the counter! • Calling a function means that you execute it, just like
} when you called the alert() function earlier in this
• A while loop is similar to a for loop insofar as the code chapter.
within the braces executes as long as the condition • Until you call a function it doesn’t really do anything,
is true. much like the alert() function doesn’t do anything
• Unlike a for loop, though, you need to explicitly do until you invoke it.
something inside of the loop in order to break out
• Calling one of your own functions looks just like the call
of the loop.
to the alert() function.
• If you forget, you’ll be stuck in an endless loop!
• Here’s that exercise we promised. Begin by opening
USING FUNCTIONS TO AVOID REPEATING YOURSELF your text editor with a new or blank document.
• A good programming practice is to reuse code • In the text editor, place the following HTML and
whenever possible. JavaScript:
• Not only does this cut down on the number of possible <!doctype html>
errors in your code, but it also makes for less work, <html>
which is always good when it comes to coding. <head>
• This section looks at a primary way to implement code <title>JavaScript Chapter 2</title>
reuse: functions. </head>
<body>
• JavaScript includes a number of built-in functions.
<h1>Here’s another basic page</h1>
};
alert(ball.color);
</script>
</body>
</html>
When viewed in a browser, you get an alert like the one shown
in Figure 2-12.
• As you can see from the alerts, the properties that were
created right along with the object are shown, as is the
weight property that was added later using the dot
notation.
• Later in this chapter, you see much more about objects,
so this bit of background will be helpful.
• When viewed in a browser, the page now looks like that Listing 2-6: Displaying the User Agent
in Figure 2-16. <!doctype html>
• Notice specifically that the text of the top line has been <html>
changed and now has a border. <head>
• In this exercise, you created HTML and JavaScript. In <title>Chapter 2</title>
the JavaScript, you accessed an HTML element using </head>
the getElementById function. <body>
• From there you displayed it using an alert(). The <div id=”output”></div>
<script type=”text/javascript”>
second part of the exercise saw you change the var outputDiv = document.getElementById(“output”);
element’s contents using innerHTML and also change outputDiv.style.border = “3px solid black”;
the CSS style of the element using the style.border outputDiv.style.padding = “3px”;
var userAgent = navigator.userAgent;
property. outputDiv.innerHTML = “You are using “ + userAgent;
</script>
</body>
</html>
• When viewed in a browser, the output looks like that
in Figure 2-17.
• Note that if you run this code, your browser version will
likely be different than this.
▪ A CDN-hosted version means that • That reference is usually added in the <head> portion
the jQuery file sits on someone of a page.
else’s server and you just • Listing 3-1 shows a page with the jQuery script
reference it in your code. referenced in the <head> section
• Whether you use a local copy of a CDN is up to you.
• For production websites, we strongly recommend Listing 3-1: Adding jQuery to a Page
using a local copy of jQuery for speed and <!doctype html>
reliability. <html>
• However, in development, like when you’re following <head>
along in this book, it’s okay to use the CDN version of <title>jQuery</title>
jQuery. <script type=”text/javascript”
• The book’s examples use a CDN-hosted jQuery, but src=”jquery-1.8.1.min.js”></script>
this section shows how to use both local and CDN. </head>
<body>
INSTALLING jQuery LOCALLY <h1>Adding jQuery</h1>
• jQuery is available as a download from </body>
www.jquery.com. </html>
• Once there, select the Production version and
click Download. • That’s all there is to adding jQuery. Later in this
• Depending on your browser’s settings you may end up chapter, you find out what to do now that it’s loaded.
with a page full of JavaScript code. ADDING CDN JQUERY TO A PAGE
• If that’s the case, select Save As from the File menu. • Loading CDN-hosted jQuery is just like loading it
o In other cases, you’ll simply be prompted to locally, minus the part where you have jQuery stored
download a file. on your hard drive, of course.
o In the end, you want to end up with a file o Other than that detail, you simply add
named like jquery-1.8.1.min.js, regardless jQuery like any other external JavaScript
of whether you save the file or download it. file.
• The file should be placed into your document root. • Here’s an example:
o Remember the filename; you’ll need it later.
• That’s all there is to installing jQuery — download it <script type=”text/javascript”
and put the file into your document root. src=”http://ajax.aspnetcdn.com/ajax/
jQuery/jquery-1.8.1.min.js”>
USING CDN-hosted jQuery </script>
• The CDN-hosted option for jQuery is great for
development. • But how do you find out the secret location where
• You don’t have to worry about downloading the file or jQuery is hosted for public use?
putting it in the right place; it’s always available (as • Go to http://jquery.com/download and you can
long as the CDN is up). find a CDNhosted jQuery.
• CDN-hosted versions are available from many of the • Within the Download page, you see a section for CDN-
big-time players on the web, like Google and hosted jQuery.
Microsoft. • When you find one you want to use, right-click and
• You don’t need to download anything in order to use a select the Copy Link Location option or similar from the
CDNhosted jQuery, so this section is short and sweet. context menu in your browser.
You can find the links for the CDN-hosted versions at • That will copy the URL to your clipboard for later use.
www.jquery.com/download. • A full page example with CDN-hosted jQuery looks
• The next section shows how to add CDN-hosted strikingly similar to the page for the locally hosted
jQuery to your page. copy, only the src attribute has changed.
ADDING JQUERY TO A PAGE Listing 3-2 shows the HTML and JavaScript; note specifically the
• Now that you have jQuery downloaded or know where <script> tag in the <head> section.
to find the CDN-hosted version, you need to
reference it in your page. Listing 3-2: CDN-hosted jQuery
• jQuery is just like any external JavaScript file which <!doctype html>
you see in Chapter 1 of this minibook. <html>
• This section shows how to add jQuery to your page <head>
both for locally hosted jQuery and CDN-hosted jQuery. <title>jQuery</title>
<script type=”text/javascript”
Adding local jQuery to a page src=”http://ajax.aspnetcdn.com/ajax/
• In the preceding section, we instruct you to download jQuery/jquery1.8.1.min.js”>
jQuery and place it in the web server’s document </script>
root. If you don’t remember the filename, locate it in </head>
your document root.
• It’ll be named like jquery-1.8.1.min.js. (Note that the <body>
version number will almost certainly be different by the <h1>Adding jQuery</h1>
time you read this.) </body>
• Adding jQuery to a page means adding an external </html>
script reference, like this:
<script type=”text/javascript” src=”jquery-1.8.1-
min.js”></script>
INCORPORATING THE jQuery ready() Function • This includes jQuery from Microsoft’s CDN into the
• A common problem when programming JavaScript is page.
that the JavaScript program will run before the • The next area of interest is within the <body>,
page is loaded. specifically, the <script> within the body:
• The preceding chapter explains that you can access
HTML elements on a page. <script type=”text/javascript”>
o This means you can also access things $(document).ready(function() {
like images, forms, and whatever else you alert(“hi”);
want, on a web page. });
</script>
• The problem comes in when you try to access
something on the page before the browser has it • This code calls the jQuery ready() function, part of
loaded. the document object.
• jQuery offers ways around this, which you see in this • Notice the special syntax with the dollar sign and
section. parentheses.
• jQuery has a function called ready() that waits for • This is what tells the browser and JavaScript that
the page to be, well, ready. what follows is going to be jQuery, so processing is
o Not quite everything is available (for handed over to jQuery.
example, some images still may be loading), o And because jQuery has a function called
but the HTML elements are ready to be ready(), it knows what to do.
worked with when the ready() function is
called. REMEMBER
• When you program with jQuery, it’s typical to place • You use $() all over the place with jQuery; it’s what
your code inside of the ready() function so that tells jQuery that it should pay attention.
you can ensure that all the stuff on the page is ready • Inside of the jQuery ready() function there’s this
for you to use in your program. code:
• Really, there’s not that much to this, so try not to function() {
overthink it. alert(“hi”);
• An example would help illustrate! }
Listing 3-3 shows an HTML page with JavaScript inside of the • You know all about functions already so this isn’t
jQuery ready() function. anything new.
• Or is it? If this is a function, where’s the function name?
Listing 3-3: Using the jQuery ready() Function For most uses of jQuery, you’ll see similar syntax to
<!doctype html> what you see here, with a function with no name like
<html> this one and then code within it.
<head>
<title>jQuery</title> TECHNICAL STUFF
<script type=”text/javascript” • When you see this syntax, function(), with no
src=”http://ajax.aspnetcdn.com/ajax/jQu name, it’s called an anonymous function.
ery/jquery1.8.1.min.js”> • For the most part, you don’t need to know much about
</script> anonymous functions until you get much deeper into
</head> JavaScript programming.
<body> • For what you’re doing here, just know that this is the
<h1>Adding jQuery</h1> typical syntax that you use when you use jQuery.
<script type=”text/javascript”>
• Within the function an alert is displayed.
$(document).ready(function() {
• No surprise here — it’s the standard alert() function
alert(“hi”);
}); you’ve been using throughout the book.
</script> • But what’s happening here is important:
</body> o You’re using jQuery together with
</html> JavaScript inside of the same script.
When viewed through a browser, the result is an alert like the SELECTING ELEMENTS WITH jQuery
one in Figure 3-1. • The preceding section explains how to select the
document object.
• It also provides a great deal of how jQuery works.
• When you use the code $(document), you use
something called a selector.
• Most of what you’ll do in jQuery happens through
selectors.
• For instance, you’ll frequently select a piece of a
• This code has two areas of interest. web page and then have jQuery perform an action
o The first is the <script> element itself: on that piece of the page.
• That action could be anything from adding text,
<script type=”text/javascript” changing HTML, changing CSS or, well, just about
src=”http://ajax.aspnetcdn.com/ajax/jQu anything you can think of!
ery/jquery1.8.1.min.js”>
</script>
The basic flow for JavaScript programming with jQuery is this: FILTERING
1. Select an element on the web page (or the entire page itself). • One additional thing you should know about jQuery
2. Do something interesting with that element. selectors is that you can filter them.
• This is particularly handy when it comes to working
• Okay, what you do with the element doesn’t have to be with forms and events.
interesting, but you will do something with the selected • With that in mind, we save the discussion of filtering
element. until we get to forms and events in the upcoming
• That something can be anything from removing the chapters.
element to adding or changing it or simply getting
information from the element, like its text or current WORKING WITH HTML USING jQuery
CSS styles. • You can use jQuery to do all kinds of fun things with
the HTML on a page and we hint at some of those
jQuery SELECTORS UP CLOSE
things, like adding HTML to a page or changing text,
• There are three primary or basic selectors in
and so on. It’s time to learn how to do it!
jQuery. We call them primary or basic because they’re
the ones you’ll use most frequently. You can set up ADDING HTML TO A PAGE
very complex selectors based on the structure of the • jQuery can be used to add HTML to a page.
page, but most often you’ll use one of these three o You can add all sorts of HTML, images, just
selectors: about anything, and completely change the
o By class layout of the page using jQuery.
o By ID • Doing so isn’t really a good idea, though, because it
o By element can get really, really confusing to figure out what’s
• If you had some HTML that looked like this: coming from where and also can be more difficult to
<p id=”bookTitle”>My Book</p> maintain in the future when you need to change the
• You could access that with jQuery like this: page.
$(“#bookTitle”) • In any event, adding HTML for things like error
messages or in order to add data to a page is quite
REMEMBER common.
• It’s important to note that things in jQuery (and o Think about a travel site that looks up flight
JavaScript) are case sensitive. information.
• So booktitle is not the same as BOOKTITLE and not • You click a button and it builds the results
the same as bookTitle. dynamically, right on the same page.
• It doesn’t matter what case you use, as long as it • Those sites use JavaScript, many times jQuery, to
matches between the HTML and the JavaScript and accomplish this feat. But before you go changing
jQuery. HTML you should learn how to add HTML to a page.
• Now take a look at this bit of HTML:
Listing 3-4 shows a simple HTML page that creates a list of
<p class=”titleClass”>This is some text</p>
items.
• The jQuery selector looks like this:
$(“.titleClass”) Listing 3-4: HTML with a List
• If you think that these selectors look like their CSS <!doctype html>
counterparts, you’re right. <html>
• Don’t worry if you weren’t thinking that; there won’t be <head>
a quiz. <title>jQuery</title>
• In CSS, you access items by their ID with a pound </head>
sign (#) and you access classes with a single dot <body>
(.): <h1>Adding HTML</h1>
#bookTitle <ul id=”theList”>
.titleClass <li>Here’s 1</li>
<li>Here’s 2</li>
• All you’re doing for jQuery is wrapping it in the $() </ul>
construct and using some quotes too. </body>
• So you get this: </html>
$(“#bookTitle”)
$(“.titleClass”) A page viewed in a web browser looks like the one in Figure 3-
• The other frequently used selector grabs all the 2.
elements of a certain type.
• The following selector selects all <div> elements on
the entire page:
$(“div”)
• There are more advanced selectors.
o For example, you can select by an element’s
position on the page and, well, just about any
combination that you can think of.
o But you’ll use these three most often and
where you need more, we’ll show them to
you.
• The page uses an unordered list with two items. • For example, say you wanted to change the text of the
o You can add another item to that list with elements in the page that you just worked on.
the jQuery append() function. • Instead of having each element say “Here’s,” you want
• Doing so means selecting the <ul> element, which it to say “Item.”
you already know how to do, and then calling the • You could add an ID to each element and then
append() function. Here’s an example to add a third change the HTML with the html() or the text()
item to the list: function.
$(“#theList”).append(“<li>Here’s 3</li>”); o But that seems like a lot of work. And it
• As you can see, you select the <ul> element using an creates another problem if the HTML changes
ID selector and then call the append() function with somewhere along the way.
the HTML to add. • Another way, and the way that we show, is to loop
• Doesn’t get much simpler than that. through each of the list items and change them.
• The preceding chapter explains loops.
Listing 3-5 shows the final code. o jQuery has its own way to loop, called
Note that jQuery has been added to it in the <head> section each().
and the append() function is within the ready() function, as • The each() loop method has an advantage over the
discussed earlier. while and for loops:
Listing 3-5: Adding an Item with jQuery o The each() function can be used with
<!doctype html> jQuery so you get the full advantage of all the
<html> jQuery functions and you can chain the
<head>
each() function with other jQuery
<title>jQuery</title>
functions.
<script type=”text/javascript”
src=”http://ajax.aspnetcdn.com/ajax/ • Chaining is the term used with jQuery to describe
jQuery/jquery1.8.1.min.js”> what you do when you connect functions with dots
</script> in order to make the function apply to the chain.
</head> • We start this example with the HTML from Listing 3-5.
In fact, we leave the append() function in there to
<body> show that the change you’ll make applies not only to
<h1>Adding HTML</h1> the HTML that was originally on the page, but also to
<ul id=”theList”> HTML that you add.
<li>Here’s 1</li> • Granted, with just two elements to change, you’d just
<li>Here’s 2</li> do this in the HTML itself, but this example shows the
</ul> process and functions for changing HTML so that you
can use it when you really need it.
<script type=”text/javascript”> Listing 3-6 shows the HTML and JavaScript for this example.
$(document).ready(function() {
$(“#theList”).append(“<li>Here’s 3</li>”);
Listing 3-6: Changing Text with each()
});
</script> <!doctype html>
</body> <html>
</html> <head>
<title>jQuery</title>
When viewed in a browser, the result looks like Figure 3-3.
<script type=”text/javascript”
src=”http://ajax.aspnetcdn.com/ajax/
jQuery/jquery1.8.1.min.js”>
</script>
</head>
<body>
<h1>Adding HTML</h1>
<ul id=”theList”>
<li>Here’s 1</li>
<li>Here’s 2</li>
</ul>
<script type=”text/javascript”>
$(document).ready(function() {
$(“#theList”).append(“<li>Here’s 3</li>”);
$(“#theList li”).each(function() {
var existingText =
$(this).text().substr(7,1);
$(this).text(“Item “ + existingText);
CHANGING ELEMENTS });
• Adding with append() makes sense; });
</script>
o you select the element that you want and
</body>
then append more HTML onto it.
</html>
• But what about when you want to change something
that already exists? • The JavaScript and jQuery here shows a few new
• There are a few ways to do it, depending on what you things, so look a bit closer at the code.
want to change. • The first line of the new code is this:
$(“#theList li”).each(function() {
• That line uses a selector to find all <li> elements CHANGING ATTRIBUTES AND STYLES
within the ID of theList. • jQuery makes retrieving and setting HTML
• That’s a little different than the other selectors you see attributes and CSS styles easy.
in the chapter and represents how jQuery can use the o This means you can change things like an
page’s hierarchy to access only the items that you image source or a CSS class or even CSS
want. styles themselves. This section looks at how
• The each() function is changed onto the selector to do just that.
and sets up an anonymous function. READING ATTRIBUTES
• At this point, you know that the code will begin looping • Remember from way, way earlier in this book (provided
through each <li> element within the ID of theList. you read earlier chapters before this one), you learned
• The next line of code looks like this: that the descriptive stuff contained inside of an HTML
var existingText = $(this).text().substr(7,1); element is called an attribute.
• This code sets up a plain JavaScript variable, • For example:
existingText, and sets it equal to the result of <a id=”exLink” class=”link”
href=”http://www.example.com”>Web site</a>
$(this).text().substr(7,1).
• The id, class, and href parts that you see in that <a>
• But what’s this, or more appropriately, $(this)?
element are all attributes.
• The special selector $(this) refers to the current
• Using jQuery, you can find out the values for all
element being worked on.
those attributes, and as you see later, you can set
o JavaScript has an equivalent called this,
them too
but you want the jQuery version, so you wrap
• Reading an attribute with jQuery means using the
it in the dollar sign/parentheses notation.
attr() function.
• The $(this) selector is chained to the jQuery
text() function, which retrieves the elements text, Listing 3-7 shows code using attr() to read the href attribute
with no HTML markup, just the text. from the link you just saw.
• The text()function is then chained to the substr() Listing 3-7: Using the attr() Function
function. <!doctype html>
o The substr() function grabs a substring, or <html>
portion of a string, and returns it. <head>
o In this case, you want substr() to return to <title>jQuery</title>
you one single character beginning at the <script type=”text/javascript”
seventh position. src=”http://ajax.aspnetcdn.com/ajax/
• You can do this because you know that every element jQuery/jquery1.8.1.min.js”>
begins with the word Here’s followed by a space, like </script>
this: </head>
Here’s 1 <body>
• Counting characters from the left, there are six <h1>Attributes</h1>
<a id=”exLink” class=”link”
characters in Here’s plus one character for the space.
href=”http://www.example.com”>Web
• That makes seven, so you end up with substr(7,1). site</a>
• Granted, this breaks when you get to ten items <script type=”text/javascript”>
because you’re only returning a single character. $(document).ready(function() {
• You could fancy this up by using a regular expression, alert($(“#exLink”).attr(“href”));
which you haven’t really spent time on yet, so for this });
example, leave it as is. </script>
</body>
• Okay, if you must know, you could replace the </html>
substr() function with the match() function, and it
• The bulk of the work is done on one line:
would look like this:
var existingText = $(this).text().match(/[\d]/); • alert($(“#exLink”).attr(“href”));
• Back to reality and the example, the final line of code • That line uses a selector to select the element with the
looks like this: ID of exLink and then calls the attr() function with
$(this).text(“Item “ + existingText); “href” as the argument.
• That line simply calls the text() function, but instead • The result is returned and placed in an alert(), shown
of returning text, this time you set it to “Item “ + in Figure 3-5.
existingText.
• Because you have the number of the item in the
variable existingText, it’s like you’re appending it.
• A page viewed in a browser looks like that in Figure 3-
4.
WRITING ATTRIBUTES
• Just like the text() and html() functions, you can
also set the value of an attribute using the attr()
function.
The code begins with the ready() function, which you’ve seen
before. Next up, you select the form by selecting all <form>
elements on the page. If there was more than one form you’d
likely want to give the form a name or ID so that you could select
the right one, but for this example, simply selecting by element
works.
Next up, the submit() function is called and another function
is created within it. The function’s main task is to display an alert,
which you saw.
The second line within the function, return false, is interesting for
forms. When you use return false in a form submit event,
you essentially prevent the form from submitting to the server.
Therefore, you’d only want to do this for specific reasons, like
when the form isn’t valid such as when the user hasn’t filled out
all the required fields.
When you add return false, you’re preventing the default
action. Because the default action of the form is to submit to the
server, adding return false prevents that default action from
occurring. Another way to prevent the default action is with the
jQuery preventDefault() function. You use
preventDefault in certain circumstances where return false
doesn’t do what you want. Changing the JavaScript from the
3. Save the form as form1.html in your document root. preceding example to use both preventDefault and return
4. View the page in a web browser at false looks like this
http://localhost/form1.html.
You should see a page like the one in Figure 4-1.
5. Now add the following code, just after the closing tag and
before the closing tag.
You can try this out by replacing the JavaScript from the earlier
example with that code. If you attempt to submit the form without
filling anything out in the Name field, you’ll receive an alert like
the one in Figure 4-3
This form validation is very basic. For instance, you could just
place a single empty space in that field and it would be valid. In
Book VI, you see much more about JavaScript validation and
server-side validation too
MONITORING MOUSE EVENTS
Capturing Mouse Clicks
• A common thing to do is capture mouse click events
with JavaScript. For example, when a person clicks on
an image or clicks a form element, you can react to it
to load a different image or select other form elements.
• Imagine you’ve set up a car shop where people can get
their cars customized with a few upgrades. You
specialize in adding fog lights, leather trim, and DVD
players. People can come to your website and choose
a trim level. Figure 4-4 shows a sample page for where
users select their options.
If people choose the Deluxe package, the form should check all
the Extra Options check boxes. If people choose the Plain
package, all the options should uncheck. Finally, if people
choose an individual option in the Extra Options list, then the
Custom package should be checked. This can all be
accomplished with a few lines of JavaScript and jQuery.
Listing 4-2 shows the HTML, CSS, and JavaScript to create the
desired behavior.
While this example shows how to work with forms and the click
event, you can actually attach a click event handler to any
element on the page. See http://api.jquery.com/click
for more information on the click event handler in jQuery
That selector looks for all <input> elements on the page but
then uses a filter to obtain only those input elements that have
the name of “trim”. In this case, those elements correspond
to the radio buttons on the form. Notice here the use of two
different quotation marks. The overall selector is enclosed in
double-quotes while the word trim is enclosed in single
quotes. You do this because otherwise jQuery would get quite
confused and think you meant to close the selector.
The selector is chained to the click() function that handles
click events. Within the click() function, the value of the item that
was clicked is examined:
That’s done through the $(this) selector and the val()
function. If that value is “deluxe”, then all the check boxes are
checked with this line:
That line again uses a selector and filter, but this time gets all
the check boxes with the name “option”. The selected check
boxes are then checked, thanks to the attr() function that the
preceding chapter explains
An else if is then used to see if the Plain radio button was
selected:
else if ($(this).val() == “plain”) {
If that radio button is selected, then the ‘option’ check boxes Pages viewed in a browser look like the one in Figure 4-5.
are unchecked.
$(“input[name=’option’]”).attr(“checked”,false);
To create this effect, the following JavaScript is employed within type your message only up to a certain number of
the page, at its usual location just above the closing </body> characters.
tag.
Listing 4-4 shows some example HTML for creating a small text
box, called a text area in HTML parlance.
The result, with the mouse hovering over the element labeled
Box 2, is shown in Figure 4-6. The box turns gray (#abacab)
The last thing to do is place that value into the <span> element
that shows the characters remaining
Now when you type into the textarea, the number of characters
remaining counts down. Figure 4-8 shows an example.
Now you know how they do this on Twitter! However, if you type
a whole bunch into the form you’ll notice that you can actually A page viewed in a browser looks like that in Figure 4-10.
continue typing past the 50 characters. The counter will go into
negative numbers (see Figure 4-9)
REMEMBER In reality, a billing info page would capture more information, like
Because you end up checking the number of characters in your the state and ZIP code for starters, but this gives you a bit of an
PHP program anyway, it isn’t the end of the world if a user goes idea of the type of page you’re setting up for this example.
past the maximum allowed. You can also prevent users from Adding JavaScript to disable those textboxes looks like this:
submitting the form. We tell you how to do those things Book VI.
Listing 4-5 shows an HTML snippet for such a page. The code begins with the ready() function, of course. After
that, a click event handler is added to the check box. If the
billingAddress check box is checked, then the values from
the form fields are cleared and those form fields are disabled. If
the billingAddress check box is unchecked, then the
disabled attribute is removed, thanks to the removeAttr()
function. Note in this example the use of classes on the text
fields to be disabled. Using classes, called “baddr” for this
example, makes it easy to group them for a jQuery selector.
CHAPTER 5: TROUBLESHOOTING variable and not its contents. You could also get fancy and
JAVASCRIPT PROGRAMS concatenate them
In This Chapter
✓ Understanding basic troubleshooting techniques
✓ Installing and using Firebug That code would show not only friendly text, but also the value
of the variable itself.
You’ve made it really far in this book and you’ve created a lot of
web pages and done some programming too. Everything you’ve WARNING
learned so far has been teachable. It’s been consistently Be mindful of using alerts in a loop structure since you need to
possible to show an example and explain it. Now you’re going dismiss each one manually in the browser. Also be sure to
to get into something that doesn’t lend itself to teaching: good remove any alerts prior to releasing the code for production use
troubleshooting techniques. on your real website. If you don’t, website visitors will find the
site really annoying.
Sure, certain aspects of troubleshooting are teachable, and this
chapter shows and explains them. But even knowing these Using comments in JavaScript
techniques won’t solve all the problems that you’ll encounter. It’s • Comments help with documenting code, which can be
still up to you to apply the techniques here. greatly helpful when you need to update or change the
code later. You can also use comments to help with
Employing Basic JavaScript Troubleshooting Techniques troubleshooting.
• The primary technique for troubleshooting technical TIP
problems is to stop. Stop what you’re doing and remain • Comments are not only useful for documenting the
calm. We’ve seen countless very smart people falter code, but they can also be helpful for troubleshooting.
when things go wrong — and things do go wrong. For example, if you’ve identified a problematic area of
the code you can comment that part out temporarily in
TIP order to get past the problem.
• So we repeat: The best piece of advice that we can give for
troubleshooting is simply to stop and remain calm. In JavaScript, comments come in two forms.
• Once you’ve done that, look at the problem from different • //: You can use a double slash as a single line
angles and reduce it to small parts. For example, you’ll comment.
encounter problems with web pages that you’re programming. • /* and */: You can use the slash-asterisk format for
The problem could be that the page isn’t loading, the page
doesn’t look right, or something else. Consider whether the
comments that span multiple lines.
problem is with the database, with the PHP, with the server, Here’s an example of the single line comment
with the JavaScript, or none of those — or more than one.
• If you think the problem is with the JavaScript, take the
JavaScript out of the page entirely. Then slowly add it back in.
Another way to troubleshoot JavaScript is by adding the
alert() function in various places. As you do your
troubleshooting, you can add comments in the code to help In this example, the first line that begins with two slashes will be
with your troubleshooting efforts. Later in this chapter, we ignored by the JavaScript interpreter but it will create and assign
show you a plug-in for Firefox that helps immensely when it the variable in the next line because that’s not commented out.
comes to troubleshooting JavaScript
You can comment lines of code out. So in the preceding
Adding alerts example, if you wanted to comment out the var myVariable =
You’ve seen and used the alert() function throughout the 77 line, you’d simply add two slashes in front of the line, like
book. A good way to troubleshoot JavaScript is by using the this
alert() function within the code to show the value of variables or
simply to show where you are in the code.
A common occurrence with JavaScript is that you’ll have a long Anything that appears after the two slashes up to the end of the
program and you won’t be able to quite figure out why the line is considered a comment and ignored.
program isn’t getting all the way through. Adding an alert on line
1 of the program can show you whether or not it’s even getting If you want to comment out multiple lines or create a multi-line
called. Then adding an alert on line 50 will show if the program comment, you use a single slash with an asterisk to open the
is getting that far. If it isn’t, then you know that there must be a comment block and then an asterisk and single slash to close
problem somewhere between line 1 and line 50. Adding alerts is the block. Anything appearing between these will be ignored.
an easy and efficient way to help in troubleshooting complex Here’s an example.
problems. You simply add code like this:
WARNING
JavaScript can be seen by everyone viewing the source of your
web page, so be careful what you display in the comments.
Placing sensitive (or offensive) information in the comments of
the code can get you in trouble
Identifying JavaScript Problems with Firebug
• Alerts and comments work well as troubleshooting tools in
JavaScript. However, an indispensable tool for the JavaScript
programmer is a tool called Firebug, which is an add-on to the Using Firebug
Firefox web browser. It contains advanced JavaScript
debugging tools as well as several other tools related to web
• When Firebug is loaded, it gets put into the toolbar in Firefox.
The Firebug icon is typically found in the upper-right corner of
development. Firebug identifies problems with JavaScript
Firefox. See Figure 5-3 for an example of what the Firebug
code as it executes and helps to quickly find solutions.
icon looks like; we’ve added an arrow to point at the icon
• This section looks at how to install Firebug and then how to
use it. We assume that you have Firefox already installed. If
you don’t, go get it at www. mozilla.org before you
continue with the next section.
TIP
• Firebug isn’t the only tool that can be used for debugging.
Internet Explorer has a tool called F12 Developer Tools, and
Chrome has its own set of developer tools too. However,
Firebug is quite robust and easy to use, so that’s what we Clicking on the Firebug icon reveals the Firebug console, shown in
cover here. Figure 5-4, for whatever page you’re currently on.
Installing Firebug
• You install Firebug as an add-on for Firefox. Installation is
straightforward but does require restarting Firefox afterwards.
Follow this procedure to install Firebug.
TIP
• Although, this procedure may change slightly by the time you
read this, the overall process is the same: Use Firefox to
download and install the Firebug add-on. However, the You can click on the various tabs within the Firebug interface to see
locations and names of links may change some of the options. When debugging JavaScript, you’ll frequently use
the Console Panel. However, the Console Panel may be disabled by
1. Open Firefox. default, like the one in Figure 5-5
2. Navigate to http://getfirebug.com.
3. On the Firebug home page, click Install Firebug (or similar link/
button, if the verbiage changes by the time you read this).
4. On the Downloads page, click to download the recommended
version of Firebug.
This will usually be the top link for newer versions of Firefox. You initiate
the download process by clicking the Download link, which takes you to
the Add-ons page.
5. On the Mozilla Add-ons page for Firebug, shown in Figure 5-1,
click the Add to Firefox button.
Firebug will download and install. Enabling the Console Panel involves clicking the down arrow next to the
6. In the Software Installation dialog shown in Figure 5-2, click word Console and selecting Enabled. When you do so, the Console
Install Now. Panel will be enabled. However, you need to reload the page in order
7. When you are prompted to restart Firefox, click Restart Now. for any errors or other information to show up in the Console Panel.
Firefox will restart and you’ll be shown the Firebug home page again. Pressing the Ctrl+R or Command+R key combination reloads the page
in Firefox.
Congratulations. Firebug has been installed. Now take a spin around the
block with it The same process is needed to enable other panels in Firebug, such as
the Net Panel. The Net Panel shows the retrieval of elements on the
page, including all JavaScript, CSS, images, and other elements. It also
If you’re using Firebug or the Chrome browser, you can also take
advantage of another means for troubleshooting, called console.log.
Using console.log, the results of whatever you’re debugging are shown
within the developer tools area’s Console tab. The console.log feature
is used like an alert:
Spend some time with Firebug to get to know its uses and how it can
help with your JavaScript programming. Once you get familiar with the
tool, it will become indispensable for you