0% found this document useful (0 votes)
22 views

gf-cpe06-midterm-transes-backup

The document is a midterm study guide for the Online Technologies course at Southern Luzon State University, focusing on JavaScript programming. It covers the basics of JavaScript, its integration into web pages, and key programming concepts such as variables, functions, and syntax. The guide emphasizes the importance of understanding JavaScript's role in enhancing user experience on websites.

Uploaded by

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

gf-cpe06-midterm-transes-backup

The document is a midterm study guide for the Online Technologies course at Southern Luzon State University, focusing on JavaScript programming. It covers the basics of JavaScript, its integration into web pages, and key programming concepts such as variables, functions, and syntax. The guide emphasizes the importance of understanding JavaScript's role in enhancing user experience on websites.

Uploaded by

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

Southern Luzon State University

COLLEGE OF ENGINEERING BATCH 2027


Online Technologies
CPE06 – MIDTERM
BSCPE II - GF | 2ND SEMESTER |

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:

2 I CPE06 – 2ND SEMESTER | Midterm


jtmh & jeanni

o the words and grammar that make up the REMEMBER


language. • The line of JavaScript ends with a semicolon.
• JavaScript is viewed through a web browser and • That’s an important concept and should be a primary
programmed in a text editor, just like HTML and takeaway from this exercise:
CSS. o You end almost every line of JavaScript
• The examples you see throughout this chapter can be with a semicolon.
programmed just like any of the other examples you
see throughout the book. ADDING COMMENTS
• In this chapter, you’ll see how to build a JavaScript • Just like the alert function is useful, so too are
program, including some of the ins and outs of comments, which are like sticky notes for your code.
programming in JavaScript. • A comment can be used so that you remember what a
certain piece of code is supposed to do or can be used
GETTING STARTED WITH JAVASCRIPT PROGRAMMING to skip over parts of the code that you don’t want to run.
• Since this might be your first exposure to programming • A common form of comment begins with two slashes,
of any kind, this section starts with some basic like this:
information to get you up to speed.
// This is a comment
SENDING AN ALERT TO THE SCREEN
• You can use JavaScript to send an alert to the screen. • You see that form of comment in the preceding
• Although this isn’t used much on web pages, you do chapter.
use it for troubleshooting your programs, and it’s a • The words that follow the two slashes won’t be read by
quick way to see JavaScript in action too. the web browser, but they can be read by people
• Begin by opening your text editor with a new or blank viewing your JavaScript so keep it clean!
document. • Another type of comment
• In the text editor, place the following HTML and o begins with a front slash and an asterisk,
JavaScript: like this /*,
• Begin by opening your text editor with a new or blank o closes with an asterisk and a front slash, like
document. this */.
• In the text editor, place the following HTML and • With that style of comment, everything in between the
JavaScript: opening and closing comment isn’t read.
/*
<!doctype html> This won’t be read, it’s in a comment
<html> */
<head>
<title>Another Basic Page</title> HOLDING DATA FOR LATER IN VARIABLES
</head> • When you work with a programming language like
JavaScript, you frequently need to hold data for later
<body> use.
<h1>Here’s another basic page</h1> o You’ll get a value, such as input from a form
<script type=”text/javascript”> that the user fills out, and then you’ll need to
alert(“hello”); use it later.
</script>
</body> REMEMBER
</html> • To hold data, you use a variable, which keeps track
of the data that you tell it to store for the lifetime of
• Save the file as basic.html in your document root.
your program.
• View the page by opening your web browser and
• That’s an important concept:
navigating to http://localhost/basic.html.
o The contents of a variable only live as long as
• You should see a page like that in Figure 2-1. your program.
o Unlike data in a database, there’s no
persistence for variable data.
• Variables are defined in JavaScript with the var
keyword, short for variable.
var myVariable;
WARNING
• JavaScript is case sensitive.
o You see in the example that the var keyword
is lowercase and
• Click OK to dismiss the alert. o the variable myVariable uses mixed case.
• Congratulations, you’re now a JavaScript programmer! • It’s important to use the same case for variable
• Looking at that program, contained in a single line names and always be aware that, for instance,
between the opening and closing <script> tags, MYVARIABLE is not the same as myVariable or
there’s just the word alert with the word “hello” myvariable.
enclosed in quotes and parentheses. • Always follow case sensitivity for JavaScript, and
• The word alert is actually a built-in function (more on you’ll never have a problem with it!
functions later in the “Using Functions to Avoid • When you create a variable, it’s common to give it
Repeating Yourself” section). some data to hold onto.
o You do this with the equals sign:

3 I CPE06 – 2ND SEMESTER | Midterm


jtmh & jeanni

CREATING STRINGS TO KEEP TRACK OF WORDS


var myVariable = 4;
• When you place words in quotes in JavaScript you
• That bit of code sets the variable named myVariable create what’s called a string.
equal to the number 4. • It’s typical to place the contents of strings into
• If you don’t set the variable right when you create it, like variables, like this:
in that example, you can set it any time merely by var aString = “This is a string.”;
setting it equal to the value that you want.
• Here’s an example: • Strings can contain numbers, and
o when you put a number in quotes it will be a
var myVariable;
string.
myVariable = 4;
• The key is the quotes, as shown here:
• You can take a spin with variables by modifying the var anotherString = “This is more than 5 letters
JavaScript you created in the preceding exercise to long!”;
look like that in Listing 2-1.
TIP
Listing 2-1: Trying Out a Variable • Strings can be enclosed in single quotes or double
<!doctype html> quotes.
<html> • Strings can be put together using the plus sign (+), as in
<head> the exercise you’re about to work through.
<title>JavaScript Chapter 2</title> • Joining strings is called concatenation, and we talk a little
</head> more about that when we tell you about joining strings in Book
IV, Chapter 1.
<body> • To practice creating a concatenated string, begin by opening
<h1>Here’s another basic page</h1> your text editor with a new or blank document. In the text
<script type=”text/javascript”> editor, place the following HTML and JavaScript:
var myVariable = 4;
alert(myVariable); <!doctype html>
</script> <html>
</body> <head>
</html> <title>JavaScript Chapter 2</title>
</head>
• If you view that code in a browser, you’ll see an alert
like the one shown in Figure 2-2. <body>
<h1>Here’s another basic page</h1>
<script type=”text/javascript”>
var myString = “Partly” + “Cloudy”;
alert(myString);
</script>
</body>
</html>

• 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;

4 I CPE06 – 2ND SEMESTER | Midterm


jtmh & jeanni

• Subtraction is accomplished with the minus sign (-) </body>


• Division with the front slash (/) </html>
• Multiplication with the asterisk (*) • Save the file as cond.html in your document root, and
view the page in a browser by going to
//Subtraction http://localhost/cond.html.
var subtraction = 5 - 3;
• You should see an alert like the one in Figure 2-4.
//Division
var division = 20 / 5;
//Multiplication
var multiply = 2 * 2;
TESTING THINGS WITH CONDITIONALS
• With a few pages of JavaScript primer done, it’s time
to look at a way to make decisions with JavaScript.
o These decisions are called conditionals.
• A good way to explain them is by explaining Steve’s
thought process around mowing the lawn: • Click OK to dismiss the alert.
o If it’s greater than 75 degrees, then it’s too • To see how the program responds when you change a
hot to mow. value, within the editor, change the value for
o If it’s raining, then he can’t mow. Otherwise, temperature to 70.
he can mow the lawn. • Here’s the code; the line that changed is in bold:
• This can be set up in JavaScript something like this: <!doctype html>
<html>
if (temperature > 75) { <head>
alert(“It’s too hot to mow”); <title>JavaScript Chapter 2</title>
} else if (weather == “raining”) { </head>
alert(“It’s raining, can’t mow”); <body>
} else { <h1>Here’s another basic page</h1>
alert(“Gotta mow”); <script type=”text/javascript”>
} var temperature = 70;
var weather = “raining”;
• That little bit of code reveals all you need to know about if (temperature > 75) {
conditionals in JavaScript! alert(“It’s too hot to mow”);
• You test a condition and then do something based on } else if (weather == “raining”) {
the results of that condition. alert(“It’s raining, can’t mow”);
• When you set up a condition, you use parentheses to } else {
contain the test and alert(“Gotta mow”);
o everything that you want to happen then }
appears between the opening and closing </script>
braces. </body>
</html>
• Save cond.html.
TIP • Reload the page in your browser by pressing Ctrl+R or
• Conditionals are one of the cases where you don’t end Command+R.
each line with a semicolon. • You should see an alert like the one in Figure 2-5.
• Here’s an exercise that you can experiment with to
work with conditionals.
• Begin by opening your text editor with a new or blank
document.
• In the text editor, place the following HTML and
JavaScript:
<!doctype html>
<html>
<head> • Click OK to dismiss the alert.
<title>JavaScript Chapter 2</title> • Take a look at what happens when you change another
</head> variable.
• Within cond.html, change the weather variable to
<body> “sunny”.
<h1>Here’s another basic page</h1> • The code should look like this; again the change has
<script type=”text/javascript”> been bolded.
var temperature = 76;
var weather = “raining”; <!doctype html>
if (temperature > 75) { <html>
alert(“It’s too hot to mow”); <head>
} else if (weather == “raining”) { <title>JavaScript Chapter 2</title>
alert(“It’s raining, can’t mow”); </head>
} else { <body>
alert(“Gotta mow”); <h1>Here’s another basic page</h1>
}
</script>

5 I CPE06 – 2ND SEMESTER | Midterm


jtmh & jeanni
<script type=”text/javascript”> • Postfix operator: The final piece of the for loop
var temperature = 70; construct increments the i variable using something
var weather = “sunny”; called a postfix operator (i++), which basically
if (temperature > 75) { increments the value by 1.
alert(“It’s too hot to mow”); • In plain language, this loop creates a variable and sets it to
} else if (weather == “raining”) { 0, then it tests to see whether the variable is still less than 10.
alert(“It’s raining, can’t mow”); If it is, then the code within the block is executed.
} else { • For now, that code is merely a comment so nothing happens.
alert(“Gotta mow”); If not, then the variable is incremented by 1 and the whole
} thing starts all over again.
</script> • The first two parts of a for loop use semicolons; the last part
</body> doesn’t.
</html> • The first time through, the variable i is 0, which is (obviously)
less than 10 — and the code inside the block executes so
• Save cond.html and reload the page in your browser. that i is incremented by 1.
• You should see an alert like the one in Figure 2-6. • The next time through, the value of i is 1, which is still less
than 10, so the code in the block is executed again. This
keeps going until the value of i is 10.
• Try it out with an exercise. Begin by opening your text editor
with a new or blank document. In the text editor, place the
following HTML and JavaScript:
<!doctype html>
<html>
<head>
<title>JavaScript Chapter 2</title>
</head>
• Click OK to dismiss the alert. <body>
• If a test fails, a conditional can be set up to run <h1>Here’s another basic page</h1>
another test. <script type=”text/javascript”>
for (i = 0; i < 10; i++) {
• In the case of the example, a second test is set up to alert(“The variable i is currently set to “ + i);
look at the weather to see if it’s raining. }
• Notice the use of the double equals signs in the else if </script>
condition. </body>
• Finally, if all tests fail then a block of code can be set </html>
up so that it runs when all else fails. • Save the file as for.html in your document root.
• This is noted by the else keyword in the code • View the file in a browser by going to
sample. http://localhost/for.html.
• You’ll see a series of alerts, one of which is shown in
WARNING Figure 2-7
• It’s important to note that once a condition is true, in the
example once the temperature is greater than 75, the code in
that block will execute but none of the other conditions will be
evaluated.
• This means that none of the other code in any of the
other blocks will ever run.

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.

6 I CPE06 – 2ND SEMESTER | Midterm


jtmh & jeanni

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>

7 I CPE06 – 2ND SEMESTER | Midterm


jtmh & jeanni
<script type=”text/javascript”> • If you call it with one of the two arguments as
// Define the function something other than a number, you’ll receive an alert
function addNumbers(num1,num2) { stating that.
alert(num1+num2); • For example, if you changed the number 2 to “two”,
} you’d receive the alert shown in Figure 2-11.
// Call the function
addNumbers(49,2);
</script>
</body>
</html>
• Save the file as func.html in your document root.
• Open your browser and point to
http://localhost/func.html.
• You should see an alert like the one shown in Figure 2- REMEMBER
9. • JavaScript is case sensitive, so you need to make
sure you use isNaN() with the correct case.
• You see variations on functions throughout the
remainder of the book that help build on this
introduction.
RETURNING RESULTS FROM FUNCTIONS
• The function that you created in this section sends an
alert.
o But there are times when you want to have
the function send something back to you —
Improving the addNumbers function to do something and then return the results.
• The function that you’ve created, addNumbers(), • The return keyword is used to return results from
accepts two arguments and adds them. a function.
o But what if you send in something that isn’t a • In the addNumbers() function example shown,
number? instead of using an alert() right within the function
o The function has no way to test that and so it
you could return the result.
happily tries to add them.
• Here’s an example:
• To experiment with this, change the 2 in the call to
addNumbers to “two”, like this: function addNumbers(num1,num2) {
var result = num1+num2;
addNumbers(49,”two”); return result;
When you reload the page, you’ll see an alert like the one in }
Figure 2-10. • You can call the function just like before, but you now
need to capture the result, typically into another
variable, like this:
var myResult = addNumbers(49,2);
Listing 2-3 shows the full HTML for this example:

Listing 2-3: Returning a Value from a Function


<!doctype html>
• JavaScript includes a function to test whether <html>
something is a number. The function is called <head>
isNaN(), which stands for is not a number. <title>JavaScript Chapter 2</title>
</head>
• This can be added anywhere that you need to test to
make sure something is a number before working <body>
with it, like in the case of the addNumbers() function. <h1>Here’s another basic page</h1>
• You use the isNaN() function within an if <script type=”text/javascript”>
conditional and then react accordingly if it isn’t a // Define the function
number. Here’s an updated addNumbers() function addNumbers(num1,num2) {
• function: var result = num1+num2;
return result;
function addNumbers(num1,num2) { }
if (isNaN(num1)) { // Call the function
alert(num1 + “ is not a number”); var myResult = addNumbers(49,2);
} else if (isNaN(num2)) { </script>
alert(num2 + “ is not a number”); </body>
} else { </html>
alert(num1+num2);
} REMEMBER
} • Only one return is allowed from a function and
nothing after the return statement executes.
o Once you call a return, the function ends.

8 I CPE06 – 2ND SEMESTER | Midterm


jtmh & jeanni

OBJECTS IN BRIEF ADDING PROPERTIES TO OBJECTS


• You’ve seen arrays and how they can be used to hold • Sometimes you want to add properties onto objects
multiple values. after they’ve been created.
o Arrays hold that data using an unseen • This too can be done using dot notation, like so:
numbered index. ball.weight = 15;
o On the other hand, objects can hold • Here’s an exercise to create an object, add to it, and
multiple values but those values are then loop through it using a new kind of loop
accessed through a named index, called a constructor.
property. • Begin by opening your text editor with a new or blank
• Objects can actually do a lot more than this, such as document. In the text editor, place the following HTML
hold functions (called methods) but for this example, and JavaScript:
consider this narrow focus, using an object to hold <!doctype html>
multiple values. <html>
<head>
CREATING OBJECTS <title>JavaScript Chapter 2</title>
• Here’s an example object for a ball: </head>
var ball = { <body>
“color”: “white”, <h1>Here’s another basic page</h1>
“type”: “baseball” <script type=”text/javascript”>
}; var ball = {
“color”: “white”,
• Whereas arrays are created with square brackets, “type”: “baseball”
o objects are created with curly braces, as };
shown in the example. ball.weight = 15;
• When you define an object, you can define one or for (var prop in ball) {
more properties (akin to the elements in an array). alert(ball[prop]);
o In this instance, you created two properties, }
one called color and one called type. </script>
o The values are then set to white and baseball, </body>
respectively. </html>
o You can access objects using a single dot,
like so: ball.color • Save this as obj.html in your document root.
▪ The single dot is known as dot • View the page in a browser by going to
notation when used in this way. http://localhost/obj.html.
• You should see three alerts, like the ones in Figure 2-
Listing 2-4 shows HTML to create a ball object and display its 13
color property.
Listing 2-4: Creating an Object and Displaying a Property
<!doctype html>
<html>
<head>
<title>JavaScript Chapter 2</title>
</head>
<body>
<h1>Here’s another basic page</h1>
<script type=”text/javascript”>
var ball = {
“color”: “white”,
“type”: “baseball”

};
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.

9 I CPE06 – 2ND SEMESTER | Midterm


jtmh & jeanni

WORKING WITH HTML DOCUMENTS


• All this JavaScript programming gets put to
practical use when you start adding it to web
pages.
• JavaScript integrates into HTML and has access to
everything in a web page.
• This means that you can add HTML to a page, take it
away, or change it, all on the fly, in real time.
• In order to work together, JavaScript and HTML need
a common language so that JavaScript can know
what to do on a page.
• JavaScript and HTML work together through
• Looking at the HTML again, you can see an ID attribute
something called the Document Object Model
on the first <div> on the page.
(DOM).
• The DOM gives JavaScript access to a web page • You can use the getElementById function to access
so that it can manipulate the page. that element.
• The connection between JavaScript and HTML is o You’re saying, “Great, I can access the
through the document object. element but what can I do with it?” Glad you
• You see the document object used in this section asked.
along with other functions to access pieces of a page • When you access an element, you view its current
using JavaScript. HTML or make changes such as CSS styling or the
• The document object is actually a child of the actual contents of the element itself.
window object and there are other children that are • Try it out in an exercise.
interesting too, as you see later in this chapter. 1. Open your text editor with a new or blank document.
ACCESSING HTML WITH JAVASCRIPT 2. In the text editor, place the following HTML and JavaScript:
• You access parts of a web page, the document object,
using JavaScript functions. <!doctype html>
<html>
• You can look at a piece of the page to see what text it
<head>
has in it or change the text in the page.
<title>Chapter 2</title>
• You can also add to the page with JavaScript and
</head>
much more.
<body>
USING GetElementById <div id=”myDiv”>Hello</div>
TO ACCESS A SPECIFIC ELEMENT <div class=”divClass”>Second Line</div>
• The most specific way that you can access an <div class=”divClass”>
element on a page is to use its ID. <p class=”pClass”>This is in a
• Recall that ID attributes can be placed on any element, paragraph.</p>
and they’re (supposed to be) unique throughout the </div>
page. <div class=”divClass”>Last Line</div>
• In this way, each element that is already part of the
DOM can be accessed directly rather than b traversing <script type=”text/javascript”>
the document tree. var theDiv = document.getElementById(“myDiv”);
• Consider the HTML in Listing 2-5. alert(“The content is “ + theDiv.innerHTML);
</script>
Listing 2-5: Basic HTML for Demonstrating the DOM </body>
<!doctype html> </html>
<html>
<head> 3. Save the file as getbyid.html in your document root.
<title>Chapter 2</title> 4. Open your web browser and view the page at
</head> http://localhost/getbyid.html.
<body> You should see an alert like the one shown in Figure 2-15.
<div id=”myDiv”>Hello</div>
<div class=”divClass”>Second Line</div>
<div class=”divClass”>
<p class=”pClass”>
This is in a paragraph.
</p>
</div>
<div class=”divClass”>Last Line</div>
</body>
</html>

• That HTML, when viewed in a browser, creates a page


like the one shown in Figure 2-14
5. Click OK to dismiss the alert and close your browser.
6. Back within getbyid.html in your editor, remove the
JavaScript line that begins with alert(). Replace that line with
these two:

10 I CPE06 – 2ND SEMESTER | Midterm


jtmh & jeanni

theDiv.style.border = “3px solid black”;


theDiv.innerHTML = “This is now changed text.”;
The entire script block should now look like this:
<script type=”text/javascript”>
var theDiv = document.getElementById(“myDiv”);
theDiv.style.border = “3px solid black”;
theDiv.innerHTML = “This is now changed text.”; Listing 2-6 shows HTML and JavaScript to display the
</script> userAgent property of the navigator object.

• 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.

• You’ve now seen how to use getElementById as


part of the DOM in JavaScript, so check that one off of
your bucket list.
• It’s good to have the understanding that
getElementById is there in case you need to work
with someone else’s JavaScript.
• However, there’s a better way to work with web
pages through JavaScript and it’s called jQuery.
• You learn about jQuery in the next chapter of this
minibook. For now, savor your victory over the DOM. REDIRECTING TO ANOTHER PAGE
WORKING WITH WEB BROWSERS • You’ve probably encountered one somewhere along
• This JavaScript primer wraps up with a quick look at the way, a page that says “Click here if you’re not
JavaScript’s view of the web browser. automatically redirected” and then automatically
• As you just saw, when a page is loaded, the document redirects you anyway.
object gives a view of the page to JavaScript. o Did you ever wonder why they bother with the
• Likewise, a couple other objects give JavaScript a view “Click here” part?
of the web browser itself. ▪ That’s done in case your browser
• Using these objects, which are children of the doesn’t have JavaScript enabled.
window object, you can do things like detect what • This section shows the code for such a page.
type of browser the visitor is using and also redirect • The location object provides the capability to
the user to a different web page entirely. redirect to another page, and it’s one of the simplest
JavaScript pages you’ll ever write.
DETECTING THE BROWSER • Listing 2-7 shows the HTML and JavaScript.
• The navigator object is used to detect things about Listing 2-7: A Redirect Page
the visitor’s browser, like what version it is. <!doctype html>
• This information can be used to present a specific <html>
page or layout to the user. <head>
<title>Chapter 2</title>
</head>
<body>
<div>

11 I CPE06 – 2ND SEMESTER | Midterm


jtmh & jeanni
<a href=”http://www.braingia.org”> o For instance, where you might use
Click here if you’re not automatically getElementById,
redirected...
</a> • jQuery has things called selectors that enable much
</div> more powerful ways to access things on a web
<script type=”text/javascript”> page for JavaScript to use.
window.location.replace(“http://www.braingia • This chapter explains how to get started with jQuery
.org”); and then shows some examples using jQuery.
</script> • Subsequent chapters in this minibook and indeed in
</body> the entire book assume that you’re using jQuery in
</html> certain places, as will become obvious as you
progress.
• A page viewed in a browser looks like the one in Figure
2-18, but only for a short time. jQuery INTRODUCED
• In fact, you may not even see it before being • jQuery is quite popular.
redirected! • Although there are no accurate statistics to show how
often jQuery is used, cursory glances at popular
sites show that jQuery is all over the web.
• jQuery also makes cross-browser development
easier.
• Though you haven’t seen much of it so far (especially
if you’ve been reading this book in linear order),
support for JavaScript differs widely from browser
to browser and from version to version.
• What works in Firefox might not work at all in Internet
Explorer or might work completely the opposite.
• A favorite example of how JavaScript support differs
from browser to browser involves the handling of
dates.
• There is a certain JavaScript function that returns
the year.
• The HTML for this page simply sets up a basic <a> • For example, assuming it’s 2008 when you call the
element with a link, no JavaScript necessary. function, JavaScript is supposed to return 2008 — but
that isn’t always the case, depending on which
• Then the JavaScript uses the location.replace
browser you’re using.
object to send the user to a different page.
o When that function is used in Firefox or
o Almost nothing to it!
Safari, you receive the full year, 2008, as
• There’s more to both the navigator and location objects you’d expect.
in JavaScript. o When you use JavaScript in Internet
• For more information on the navigator object, go to Explorer, you receive the number of years
this page on Mozilla Developer Network: that have elapsed since 1900. When the year
o https://developer.mozilla.org/en-
is 2008, you’d receive 108 back from Internet
US/docs/DOM/window.navigator
Explorer.
• For more information on the location object, see this • Obviously if you’re trying to do any sort of date
page: calculation with that value, it’s going to be wildly
o https://developer.mozilla.org/en-
askew.
US/docs/DOM/window.location
o Which browser is right? It doesn’t really
matter.
CHAPTER 3: ADDING JQUERY
• What’s important is that the browser manufacturers
In This Chapter
read the JavaScript specification differently and, in the
✓ Understanding what jQuery is
end, return different things for the same function.
✓ Installing jQuery
• Unfortunately, the date example is but one of many
✓ Adding jQuery to a page
such examples (some much more serious than that)
✓ Adding HTML with jQuery
where browsers differ in how they implement
✓ Changing styles with jQuery
JavaScript.
• j Query is a JavaScript library. • The good news is that jQuery takes that
• A JavaScript library is a collection of code that you complication away.
use when you want to get access to additional • jQuery’s functions figure out what browser is being
functionality or make life easier. used in an accurate way and then account for it in
o jQuery does both. order to make the browser behave in a consistent
• jQuery is simply JavaScript that you add to your manner.
web page to make writing JavaScript easier. INSTALLING jQuery
• You still use JavaScript with jQuery, so everything • There are two ways to use jQuery, either
you learn in Chapter 2 is not wasted. o Downloaded locally
o However, there are certain things that ▪ The local copy is just that, a file that
jQuery does much better than plain old sits within your document root on
JavaScript. your server’s hard drive.
• Working with web pages is one such thing. o Content Delivery Network (CDN).

12 I CPE06 – 2ND SEMESTER | Midterm


jtmh & jeanni

▪ 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>

13 I CPE06 – 2ND SEMESTER | Midterm


jtmh & jeanni

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>

14 I CPE06 – 2ND SEMESTER | Midterm


jtmh & jeanni

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.

15 I CPE06 – 2ND SEMESTER | Midterm


jtmh & jeanni

• 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() {

16 I CPE06 – 2ND SEMESTER | Midterm


jtmh & jeanni

• 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.

17 I CPE06 – 2ND SEMESTER | Midterm


jtmh & jeanni

• For example, to change the value of the href attribute


from the code in Listing 3-7, you’d do this:
$(“#exLink”).attr(“href”, “http://www.braingia.org”);
• Images are added to a page by using the src
attribute.
• This means that you can change the src attribute to
change the image, on the fly, through JavaScript.
• Listing 3-8 contains HTML for a page.
• The HTML contains an image that loads square.jpg.

Listing 3-8: A Page with an Image


<!doctype html>
<html>
<head>
<title>jQuery</title>
</head> • Look closely at the HTML and you’ll see a problem.
<body> • You’ve successfully changed the src attribute, but the
<h1>Attributes</h1> alt attribute still says that the image is a square.
<img alt=”square” id=”theImage” src=”square.jpg” /> • You should change the alt attribute to match the image.
</body> • Doing so is as simple as calling attr() again, this
</html> time to set the alt attribute.
$(“#theImage”).attr(“alt”,”heart”);
• When viewed in a browser, the page looks like Figure • Because you never see the change, the code in Listing
3-6. 3-9 might not seem all that interesting.
• You can change that image to a different one using the • Do something to change that.
attr()unction. • Add a timer to delay the switch.
Listing 3-9 shows the code to achieve such a feat. • For this timer, use the native JavaScript function called
setTimeout.
• The setTimeout() function takes two arguments,
the function to call when the timer expires and how long
to wait.
• The time value that you use is in milliseconds, so 2
seconds is 2000 milliseconds.

Listing 3-10 shows the new code.

Listing 3-10: Delaying the Image Change


<!doctype html>
<html>
<head>
<title>jQuery</title>
<script type=”text/javascript”
src=”http://ajax.aspnetcdn.com/ajax/
Listing 3-9: Changing an Image’s Source jQuery/jquery1.8.1.min.js”>
<!doctype html> </script>
<html> </head>
<head>
<title>jQuery</title> <body>
<script type=”text/javascript” <h1>Attributes</h1>
src=”http://ajax.aspnetcdn.com/ajax/ <img alt=”square” id=”theImage”
jQuery/jquery1.8.1.min.js”> src=”square.jpg” />
</script> <script type=”text/javascript”>
</head> function changeImage() {
<body> $(“#theImage”).attr(“src”,”heart.jpg”);
<h1>Attributes</h1> $(“#theImage”).attr(“alt”,”heart”);
<img alt=”square” id=”theImage” }
src=”square.jpg” /> $(document).ready(function() {
<script type=”text/javascript”> setTimeout(changeImage,2000);
$(document).ready(function() { });
$(“#theImage”).attr(“src”,”heart.jpg”); </script>
}); </body>
</script> </html>
</body> • This code builds a function called changeImage().
</html> Inside of that function is the same line of jQuery that
Figure 3-7 shows the result. you had in the preceding example (Listing 3-9).
• Inside of the ready() function, there’s now a call to
setTimeout with the two function arguments we

18 I CPE06 – 2ND SEMESTER | Midterm


jtmh & jeanni

already mentioned, the changeImage function, and </script>


2000, for a delay of 2 seconds. </body>
• When you view this in a browser, you first receive a </html>
page like that in Figure 3-6 and then, two seconds later,
receive a page like Figure 3-7. The code simply calls attr() to change the class attribute to
borderClass.
CHANGING CSS
• You can also change the styling information on a page, In this case, there actually isn’t a class attribute on the element
either by setting the styles directly or by changing the yet, so jQuery is smart enough to just add one for you. The result
CSS class applied to an element. ends up like Figure 3-8.
• Class is just another attribute on an element, so
changing CSS means using the attr() function
again.
Adding a class
Listing 3-11 contains basic HTML with some styling information
in the <head> section.

Listing 3-11: HTML with CSS


<!doctype html>
<html>
<head>
<title>jQuery</title>
<script type=”text/javascript”
src=”http://ajax.aspnetcdn.com/ • But what to do if there’s already a class on the
ajax/jQuery/jquery1.8.1.min.js”> element?
</script> • You could first retrieve the classes using attr and then
<style type=”text/css”> append another one.
.borderClass { • Or you could use the jQuery function for adding a class,
border: 3px solid black; called addClass().
} • The addClass() function doesn’t interfere with any
</style> other classes that are already applied to an element; it
</head> just adds another class to it.
<body> • Making the change to the code from Listing 3-12 is as
<h1>Styles</h1> simple as changing the line:
<img alt=”heart” id=”theImage”
src=”heart.jpg” /> • $(“#theImage”).attr(“class”,”borderClas
</body> s”);
</html> • to:
• $(“#theImage”).addClass(“borderClass”);
• When you view the page in a browser, you end up with • With that simple change, the class borderClass will be
a page like that from Figure 3-7, with a simple heart added and you don’t have to worry about removing
image on the page. other classes that are applied to the element.
• However, by adding a call to the attr() function to
add the borderClass defined on the page, you end Removing a class
up with code like that in Listing 3-12. • A companion to the addClass() function, called
removeClass, takes the class away from an element.
Listing 3-12: Adding a Class Using attr() . • Like addClass(), removeClass() doesn’t affect
<!doctype html> other classes that are on the element; it removes only
<html> the specified class.
<head> • The syntax for removeClass is like the addClass
<title>jQuery</title>
syntax:
<script type=”text/javascript” $(“#theImage”).removeClass(“borderClass
src=”http://ajax.aspnetcdn.com/ ”);
ajax/jQuery/jquery1.8.1.min.js”>
</script>
In the next chapter, you see another related function called
<style type=”text/css”>
toggleClass that adds or removes the class, depending on
. borderClass {
border: 3px solid black; whether it’s already applied to an element.
}
</style>
</head>
<body>
<h1>Styles</h1>
<img alt=”heart” id=”theImage”
src=”heart.jpg” />
<script type=”text/javascript”>
$(document).ready(function() {
$(“#theImage”).attr(“class”,”borderClass”);
});

19 I CPE06 – 2ND SEMESTER | Midterm


jtmh & jeanni

CHAPTER 4: REACTING TO EVENTS WITH


JAVASCRIPT AND JQUERY
In This Chapter
✓ Understanding events
✓ Using JavaScript with forms
✓ Responding to mouse clicks and hovering
✓ Counting characters and disabling a form field
Events
• Events are things that happen. For example, the sun
rising is an event. The sun setting is an event. You can
choose to react to those events. For example, when
the sun rises, you might get out of bed — or you might
not. When the sun sets, you might turn on a light or
might go to bed.
Events in Web Programming
• When it comes to web programming, events are the
things that happen in a web page. For example, a user
might move the mouse over a button, click a button, or
submit a form. Like the example of the sun rising, you
can choose to react to the event or you can ignore it.
• If all you wanted to do was ignore events, then this
would be a really, really short chapter. But you probably
want to react to events, and we show you how to do so
for some common scenarios.
Understanding Events
In general, there are four types of events that you’ll be
concerned about:
Form events
• Includes things like selecting a check box or submitting
the form itself. Reacting to form events is one of the
most common things that JavaScript programmers do.
Mouse events
• This can be anything from a mouse click to mouse
movements on the page. That’s right; you can actually
track where the mouse is on a page and react to it.
Keyboard events
• Things that happen through the keyboard, like a key A page viewed in a browser looks like that in Figure 4-1.
press, are considered keyboard events.
Page events
• Things like the page loading or unloading are
considered page events. You’ll be happy to know that
you’ve already been reacting to the page load event
through the jQuery ready() function.
Working with Forms
Speaking of jQuery, this chapter concentrates largely on using
jQuery for working with events. Using jQuery saves a lot of
compatibility headaches that come into play when you start Right now, when you click Send Form nothing happens. Change
trying to make your JavaScript code work across browsers. that by following these steps.

Adding a Submit Handler 1. Open your text editor.


• jQuery includes a function that automatically watches 2. In the editor, place the following code:
for a form to be submitted.
Listing 4-1 shows HTML for a form used earlier in the book.
We’ve taken the liberty of adding jQuery to the section of the
form.

20 I CPE06 – 2ND SEMESTER | Midterm


jtmh & jeanni

You’ve added a submit event handler. Look at the code.

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.

Checking for Blank Fields


Though we include an entire chapter on validation (Book VI,
Chapter 2), here we provide a sneak peek at validating a form,
at least checking for blank fields. Consider the form from earlier
in the chapter and shown in Figure 4-1. Say that the Name field
6. Save the file, again as form1.html. was required; that means the user needs to fill something out in
7. View the page in a browser; you can also reload the page with order for the form to be sent to the server.
Ctrl+R or Command+R if you left it open from a previous step.
8. Click Send Form. • You can change the JavaScript to make sure that the
field has been filled in.
You should receive an alert like the one shown in Figure 4-2 • Recall that the ID of the Name field is “username”.
jQuery can select that pretty easily, and then it’s a
matter of getting the value for the field.
• For that, you can use jQuery’s val() function.
Finally, all you need to do is put the whole thing in an if
statement to make sure the value isn’t empty

21 I CPE06 – 2ND SEMESTER | Midterm


jtmh & jeanni

The code looks like this:

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.

22 I CPE06 – 2ND SEMESTER | Midterm


jtmh & jeanni

individually results in the Custom radio button becoming


selected.

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

Watching Mouse Movements


• There are several interesting items surrounding the
movement of the mouse or pointing device. For
instance, you can change an element when the mouse
hovers over it or when the mouse leaves the element.
Notice that the Cascading Style Sheet (CSS) is the same from
that of Listing 4-1. The HTML is straightforward, insofar as it sets This section shows a hover event handler, which handles both
up the form that you see in Figure 4-4. The JavaScript is where the hover over and when the mouse leaves the element.
things get interesting. The first thing the JavaScript does is put
everything into the ready() function. You’ve seen that numerous TIP
times already; no need for further explanation there. You can emulate the hover event handler through CSS although
The second thing in the JavaScript is a selector that is attached support for the CSS :hover pseudoclass is not available on older
to the click() event. This selector is a bit more complex than browsers.
those you’ve seen previously
Listing 4-3 shows the HTML for this example.

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);

After that click event handler is closed, another one is created.


This time, the handler is connected to the check boxes:
$(“input[name=’option’]”).click(function(event) {

If someone clicks on one of the check boxes, whether to check


it or uncheck it, you need to enable the “Custom” radio button.
That’s accomplished with this line:
$(“#custom”).attr(“checked”,”checked”);
For the hover effect, you add JavaScript to make it so that when
You can try this out with the code from Listing 4-2. When you a box is hovered over with the mouse, the background color
select Deluxe, the check boxes will automatically check and if changes.
you select Plain, they’ll uncheck. Clicking any of the check boxes

23 I CPE06 – 2ND SEMESTER | Midterm


jtmh & jeanni

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.

This code places everything in the jQuery ready() function,


as usual. Next, all items with a class of “box” are selected and
the hover() function is chained to them

Pages viewed in a browser look like Figure 4-7.


The hover() function takes two arguments: what to do when
the hover is in effect and what to do when the hover is done. So
each of those functions is created. The first one adds a class
called “colorBox”, which merely changes the background
color to a shade of gray; the CSS for that was in Listing 4-3. The
second function, applied when the mouse moves out of the
selected element, removes the class “colorBox”, as shown
here.

Adding JavaScript to count characters looks like this:

The result, with the mouse hovering over the element labeled
Box 2, is shown in Figure 4-6. The box turns gray (#abacab)

This JavaScript first sets a variable with the maximum number


of characters allowed, 50. Then the element with the ID of
“message” is selected. A event handler is attached to the
selected element. The event handler is attached with the on()
function, which is a generic event handler. The event handlers
you’ve seen so far are all so common that the folks at jQuery
created specific functions to handle them. So things like
submit(), click(), and hover() all have their own events.
However, all other events are attached using the on()
function. The first argument to the on() function is the name
of the event to watch for. In this case, you want to watch for the
REACTING TO KEYBOARD EVENTS “keyup” event to know when a key is pressed and then released
Just as you can react to mouse events, so too can you react to
keyboard events. Things like watching when a certain key is
pressed, or more generically, just counting the number of times
the keys are pressed, can all be done with JavaScript. This Now you know the maximum characters allowed, 50, and you
section looks at two examples of JavaScript to react to keyboard know the current number of characters in the field. Next up:
events. math. You need to subtract the current number of characters in
the variable currentVal from the maximum allowed
Counting Characters characters in the variable maxCharacters. The result will be
• If you’ve used Twitter, you’ve seen an example of a placed in a new variable called totalRemaining.
textbox that counts down while you type. Many contact
forms also include similar functions, where you can

24 I CPE06 – 2ND SEMESTER | Midterm


jtmh & jeanni

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.

PREVENTING CHARACTER INPUT


You can use JavaScript to disable a form field. For example,
many sites use a shipping and billing address combination
whereby the user clicks a check box to indicate that the billing
address is the same as the shipping address.

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.

25 I CPE06 – 2ND SEMESTER | Midterm


jtmh & jeanni

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:

Alternatively, if you need to show the value of a variable named


myVariable, you’d do this:
In that example, all the code will be ignored because it appears
in a comment block.
Notice the lack of quotes around the variable name. If you put REMEMBER
quotes around the variable name, JavaScript will interpret that It’s important to note when using multi-line comments that you
as a plain old string and so you’ll only see the name of the can’t nest them. For example, this is invalid

26 I CPE06 – 2ND SEMESTER | Midterm


jtmh & jeanni

Once the JavaScript interpreter encounters the end */ code, it


will assume that the comment has ended and therefore won’t
know what to do with the next */ that it encounters. You can
still use the double-slash construction, 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

27 I CPE06 – 2ND SEMESTER | Midterm


jtmh & jeanni
shows the response code, which can sometimes be helpful to show that
a certain file isn’t loading. The Net Panel also shows timing information
so you can see how long it took the browser to download the various
page elements too. The Net Panel is shown in Figure 5-6

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

PADAYON! FUTURE ENGINEERS

28 I CPE06 – 2ND SEMESTER | Midterm

You might also like