JavaScript Notes
JavaScript Notes
Client-Side JavaScript
Advantages of JavaScript
1
Limitations of JavaScript
We cannot treat JavaScript as a full-fledged programming language. It lacks the
following important features:
Client-side JavaScript does not allow the reading or writing of files. This has
been kept for security reason.
JavaScript cannot be used for networking applications because there is no such
support available.
JavaScript doesn't have any multithreading or multiprocessor capabilities.
Various vendors have come up with very nice JavaScript editing tools. Some of these tools are:
Microsoft FrontPage:
Microsoft has developed a popular HTML editor called FrontPage.
FrontPage also provides web developers with a number of JavaScript tools to
assist in the creation of interactive websites.
Macromedia Dreamweaver MX:
Macromedia Dreamweaver MX is a very popular HTML and JavaScript editor in
the professional web development crowd.
It provides several handy prebuilt JavaScript components, integrates well with
databases, and conforms to new standards such as XHTML and XML.
Macromedia HomeSite 5:
HomeSite 5 is a well-liked HTML and JavaScript editor from Macromedia that
can be used to manage personal websites effectively.
JavaScript – Syntax
JavaScript can be implemented using JavaScript statements that are placed within
the <script>... </script> HTML tags in a web page.
You can place the <script> tags, containing your JavaScript, anywhere within you
web page,
but it is normally recommended that you should keep it within the <head>
tags.
2
The <script> tag alerts the browser program to start interpreting all the text between these
tags as a script.
A simple syntax of your JavaScript will appear as follows.
<script ...>
JavaScript code
</script>
<html>
<body>
<script language="javascript" type="text/javascript">
<!--
document.write ("Hello World!")
//-->
</script>
</body>
</html>
3
Whitespace and Line Breaks
JavaScript ignores spaces, tabs, and newlines that appear in JavaScript programs.
You can use spaces, tabs, and newlines freely in your program and you are free to
format and indent your programs in a neat and consistent way that makes the code
easy to read and understand.
But when formatted in a single line as follows, you must use semicolons:
<script language="javascript" type="text/javascript">
<!--
var1 = 10; var2 = 20;
//-->
</script>
Case Sensitivity
JavaScript is a case-sensitive language.
This means that the language keywords, variables, function names, and any other
identifiers must always be typed with a consistent capitalization of letters.
Comments in JavaScript
JavaScript supports both C-style and C++-style comments. Thus:
Any text between a // and the end of a line is treated as a comment and is
ignored by JavaScript.
Any text between the characters /* and */ is treated as a comment. This may span
multiple lines.
4
JavaScript also recognizes the HTML comment opening sequence <!--.
JavaScript treats this as a single-line comment, just as it does the // comment.
The HTML comment closing sequence --> is not recognized by JavaScript so it
should be written as //-->.
Example
The following example shows how to use comments in JavaScript.
<html>
<body>
<script language="javascript" type="text/javascript">
<!--
document.write ("Hello World!")
//-->
</script>
<noscript>
Sorry...JavaScript is needed to go ahead.
</noscript>
</body>
</html>
Now, if the user's browser does not support JavaScript or JavaScript is not enabled,
then the message from<noscript>--- </noscript> will be displayed on the screen.
5
JavaScript – Placement
If you want to have a script run on some event, such as when a user clicks
somewhere, then you will place that script in the head as follows.
Example:
<html>
<head>
<script type="text/javascript">
<!--
function sayHello( )
{
alert("Hello World")
}
//-->
</script>
</head>
<body>
Click here for the result
<input type="button" onclick="sayHello()" value="Say Hello" />
</body>
</html>
Say Hello
6
JavaScript in <body>...</body>Section
If you need a script to run as the page loads so that the script generates content in
the page, then the script goes in the <body> portion of the document.
In this case, you would not have any function defined using JavaScript.
Example:
<html>
<head>
</head>
<body>
<script type="text/javascript">
<!--
document.write("Hello World")
//-->
</script>
<p>This is web page body </p>
</body>
</html>
Hello World
You can put your JavaScript code in <head> and <body> section altogether as
follows.
<html>
<head>
<script type="text/javascript">
<!--
function sayHello()
{
alert("Hello World")
}
//-->
</script>
</head>
<body>
7
<script type="text/javascript">
<!--
document.write("Hello World")
//-->
</script>
<input type="button" onclick="sayHello()" value="Say Hello" />
</body>
</html>
HelloWorld
Say Hello
There are cases where you can reuse identical JavaScript code on multiple pages of
a site.
You are not restricted to be maintaining identical code in multiple HTML files.
The script tag provides a mechanism to allow you to store JavaScript in an external
file and then include it into your HTML files.
Example of how you can include an external JavaScript file in your
HTML code using script tag and its src attribute.
<html>
<head>
<script type="text/javascript" src="filename.js" > </script>
</head>
<body>
.......
</body>
</html>
To use JavaScript from an external file source, you need to write all your JavaScript
source code in a simple text file with the extension ".js" and then include that file as
shown above.
For example, you can keep the following content in filename.js file and then you
can use sayHello function in your HTML file after including the filename.js file.
function sayHello() {
alert("Hello World")
}
8
JavaScript Language Elements
Variables
<script type="text/javascript">
<!--
var myVar = "global"; // Declare a global variable
function checkscope( )
{
var myVar = "local"; // Declare a local variable
document.write(myVar);
}
//-->
</script>
9
JavaScript Reserved Words
A list of all the reserved words in JavaScript are given in the following table.
They cannot be used as JavaScript variables, functions, methods, loop labels, or any
object
names.
Data Types
There are six data types in JavaScript :
The data type of the identifier is not assigned when the identifier is declared.
When a value is assigned to the identifier the identifier takes on that type.
10
The data type of the variable is not important until an operator is applied to the variable.
The behavior of the operator is dependent of the data type being acted upon.
For example:
var name = “Sally”
name = 34
The string, Sally, is first assigned to the variable.
Next, the integer 34 is assigned to the variable.
Both are legal but usage of the identifier is inconsistent.
It is better if we are consistent when assigning a data type to a variable.
This leads to less confusing code.
<html>
<head>
<title>JavaScript Data Conversion</title>
<script language="JavaScript 1.2">
<!--
document.write("<br>parseFloat - " + parseFloat('77.3'));
document.write("<br>parseInt - " + parseInt('77'));
document.write("<br>parseInt - " + parseInt('123.45'));
document.write("<br>Number - " + Number("2.34"));
document.write("<br>Implicit Conversion - " + ("2.34"-1));
//-->
</script>
</head>
<body>
</body>
</html>
11
A number can be converted to a string or Boolean using the String and Boolean
functions.
<html>
<head>
<title> JavaScript Data Conversion </title>
<script language="JavaScript 1.2">
document.write("<br> String - " + String(2.34));
document.write("<br> Boolean - " + Boolean(2.34));
</script>
</head>
<body>
</body>
</html>
JavaScript – Operators
Arithmetic Operators
Comparison Operators
Logical (or Relational) Operators
Assignment Operators
Conditional (or ternary) Operators
12
Arithmetic Operators
<html>
<body>
<script type="text/javascript">
<!--
var a = 33;
13
var b = 10;
var c = "Test";
var linebreak = "<br />";
document.write("a + b = ");
result = a + b;
document.write(result);
document.write(linebreak);
document.write("a - b = ");
result = a - b;
document.write(result);
document.write(linebreak);
document.write("a / b = ");
result = a / b;
document.write(result);
document.write(linebreak);
document.write("a % b = ");
result = a % b;
document.write(result);
document.write(linebreak);
document.write("a + b + c = ");
result = a + b + c;
document.write(result);
document.write(linebreak);
a = a++;
document.write("a++ = ");
result = a++;
document.write(result);
document.write(linebreak);
b = b--;
document.write("b-- = ");
result = b--;
document.write(result);
document.write(linebreak);
//-->
</script>
<p>Set the variables to different values and then try...</p>
</body>
</html>
14
Output
a + b = 43
a - b = 23
a / b = 3.3
a%b=3
a + b + c = 43Test
a++ = 33
b-- = 10
Set the variables to different values and then try...
Comparison Operators
15
Example
<html>
<body>
<script type="text/javascript">
<!--
var a = 10;
var b = 20;
var linebreak = "<br />";
document.write("(a == b) => ");
result = (a == b);
document.write(result);
document.write(linebreak);
document.write("(a < b) => ");
result = (a < b);
document.write(result);
document.write(linebreak);
document.write("(a > b) => ");
result = (a > b);
document.write(result);
document.write(linebreak);
16
Output
(a == b) => false
(a < b) => true
(a > b) => false
(a != b) => true
(a >= b) => false
Logical Operators
Example
Try the following code to learn how to implement Logical Operators in JavaScript.
<html>
<body>
<script type="text/javascript">
<!--
var a = true;
var b = false;
var linebreak = "<br />";
document.write("(a && b) => ");
result = (a && b);
17
document.write(result);
document.write(linebreak);
document.write("(a || b) => ");
result = (a || b);
document.write(result);
document.write(linebreak);
document.write("!(a && b) => ");
result = (!(a && b));
document.write(result);
document.write(linebreak);
//-->
</script>
<p>Set the variables to different values and different operators and then try...</p>
</body>
</html>
Output
(a && b) => false
(a || b) => true
!(a && b) => true
Set the variables to different values and different operators and then try...
Assignment Operators
18
/= (Divide and Assignment)
It divides the left operand with the right operand and assigns the result to
5
the left operand.
Ex: C /= A is equivalent to C = C / A
%= (Modules and Assignment)
It takes modulus using two operands and assigns the result to the left
6
operand.
Ex: C %= A is equivalent to C = C % A
Example
<html>
<body>
<script type="text/javascript">
<!--
var a = 33;
var b = 10;
var linebreak = "<br />";
document.write("Value of a => (a = b) => ");
result = (a = b);
document.write(result);
document.write(linebreak);
document.write("Value of a => (a += b) => ");
result = (a += b);
document.write(result);
document.write(linebreak);
document.write("Value of a => (a -= b) => ");
result = (a -= b);
document.write(result);
document.write(linebreak);
document.write("Value of a => (a *= b) => ");
result = (a *= b);
document.write(result);
document.write(linebreak);
19
document.write("Value of a => (a %= b) => ");
result = (a %= b);
document.write(result);
document.write(linebreak);
//-->
</script>
<p>Set the variables to different values and different operators and then try...</p>
</body>
</html>
Output
Value of a => (a = b) => 10
Value of a => (a += b) => 20
Value of a => (a -= b) => 10
Value of a => (a *= b) => 100
Value of a => (a /= b) => 10
Value of a => (a %= b) => 0
Set the variables to different values and different operators and then try...
Conditional Operator (? :)
The conditional operator first evaluates an expression for a true or false value and
then executes one of the two given statements depending upon the result of the
evaluation.
Example
Try the following code to understand how the Conditional Operator works in
JavaScript.
<html>
<body>
<script type="text/javascript">
<!--
var a = 10;
var b = 20;
20
var linebreak = "<br />";
document.write ("((a > b) ? 100 : 200) => ");
result = (a > b) ? 100 : 200;
document.write(result);
document.write(linebreak);
document.write ("((a < b) ? 100 : 200) => ");
Output
((a > b) ? 100 : 200) => 200
((a < b) ? 100 : 200) => 100
Set the variables to different values and different operators and then try...
typeof Operator
The typeof operator is a unary operator that is placed before its single operand,
which can be of any type.
Its value is a string indicating the data type of the operand.
The typeof operator evaluates to "number", "string", or "boolean" if its operand is a
number, string, or boolean value and returns true or false based on the evaluation.
Here is a list of the return values for the typeof Operator.
21
Example
<html>
<body>
<script type="text/javascript">
<!--
var a = 10;
var b = "String";
var linebreak = "<br />";
result = (typeof b == "string" ? "B is String" : "B is Numeric");
document.write("Result => ");
document.write(result);
document.write(linebreak);
result = (typeof a == "string" ? "A is String" : "A is Numeric");
document.write("Result => ");
document.write(result);
document.write(linebreak);
//-->
</script>
<p>Set the variables to different values and different operators and then try...</p>
</body>
</html>
Output
Result => B is String
Result => A is Numeric
Set the variables to different values and different operators and then try...
22
Message Boxes
Example:
var result = confirm("This is a confirm Dialog");
document.write(result);
The prompt dialog box provides a way of getting input from the user.
The prompt function has two arguments.
The first is the prompt message and
the second is a default value if any.
Example:
var result = prompt("Enter Your Name","");
document.write(result);
23
Control Structures
1. Selection
2. Iteration
1. if structure
2. if …else
3. switch
if statement
if...else statements
These allow a block of statements to be executed if the tested condition is true and
another block of statements to be executed if the tested condition is false
Example:
var age = prompt("Enter your age");
if (parseInt(age <18){
alert("You are a youth"); }
else{
alert("You are an adult"); }
24
else if statements
These allow multiple statements to be executed if the tested condition is true
Example:
var grade
var marks = prompt("Enter marks");
parseInt(marks)
if (marks< 40){
grade = ‘F’;
alert(grade); }
else if (marks< 50){
grade = ‘D’;
alert(grade); }
else if (marks< 60){
grade = ‘C’;
alert(grade); }
else if (marks< 70){
grade = ‘B’;
alert(grade); }
else if (marks< =100){
grade = ‘A’;
alert(grade); }
else {
alert(“The grade is undefined”); }
switch statements
switch(dayOfWk) {
case “Sat” :
alert("Go to church");
break;
case "Sun" :
alert("Clean the Compound");
break;
case "Mon" :
alert("Visit sick people in Kisumu Hospitals");
break;
25
case “Tue” :
alert("Supervise operations in Kenyatta Hospital");
break;
case “Wed” :
alert("Visit Dadaab refugee camp");
break;
case “Thu” :
alert("Attend to patients in Cost general Hospital");
break;
case “Fri” :
alert("Give report to ministry of Health");
break;
default :
alert("No defined role");
}
1. while
2. do…while
3. for
while loops
26
do...while loops
for loop
Functions
A function is a block of JavaScript code that does the same thing again and again,
whenever you invoke its name.
It saves you repetitive coding and makes your code easier to understand.
Example:
On your website, suppose there are several pages where you want to display an alert that
tells the user the current time. (let us use 24-hour time)
27
The function can be defined as follows:
function tellTime( ) {
var now = new Date();
var theHr = now.getHours();
var theMin = now.getMinutes();
alert("Current time: "+ theHr + ":" + theMin);
}
The time-telling code—the code that creates the Date object, extracts the time, formats it,
and displays an alert.
Calling a function
<html>
<head> <title> Function Demo3 </title>
<script type="text/javascript" >
<!--
function tellTime( ) {
var now = new Date();
var theHr = now.getHours();
var theMin = now.getMinutes();
alert("Current time: "+ theHr + ":" + theMin);
}
//-->
</script>
</head>
<body>
<script>
28
<!--
document.write(tellTime());
//-->
</script>
</body>
</html>
<html>
<head>
<title>JavaScript Example</title>
<script type="text/javascript" >
<!--
function multiply(num1, num2) {
return num1*num2;
}
//-->
</script>
</head>
<body>
<script type="text/javascript">
<!--
document.write(multiply(2,4));
//-->
</script>
</body>
</html>
29
Arrays
Creating Arrays
Accessing the elements of an array is done using the array name with square brackets and
a value.
For example, we can define a three-element array like so:
var myArray = [1,51,68];
Given that arrays in JavaScript are indexed beginning with zero, to access the first
element we would specify myArray[0].
30
The following shows how the various elements in the last array could be accessed:
var x = myArray[0];
var y = myArray[1];
var z = myArray[2];
However, you need to be careful when accessing an element of an array that is not set.
For example,
alert(myArray[35]);
results in the display of an undefined value, since this array element is obviously
not set.
However, if we wanted to set this array element, doing so is quite straightforward.
The nice thing about JavaScript arrays, unlike those in many other programming
languages, is that you don‘t have to allocate more memory explicitly as the size of the
array grows.
For example, to add a fourth value to myArray, you would use
myArray[3] = 57;
You do not have to set array values contiguously (one after the other), so
myArray[11] = 28;
is valid as well.
However, in this case you start to get a sparsely populated array, as shown by the
dialog here that displays the current value of myArray
31
Modifying the values of an array
To change the second value of the array, just assign it like this:
myArray[1] = 101;
The length property retrieves the index of the next available (unfilled) position at the end
of the array.
Even if some lower indices are unused, length gives the index of the first available slot
after the last element.
Consider the following:
var myArray = new Array( );
myArray[1000] = "This is the only element in the array";
alert(myArray.length);
32
Getting the current date and time
Your webpage includes a notice telling the user the current local date and time in his
particular time zone.
JavaScript produces this using the statement
var rightNow = new Date();
The statement above creates a Date object.
This will show:
Day of week, Month, Date, Year, Hours(24 – Hours format), Minutes, Seconds,
Milliseconds, Offset from Greenwich Mean Time, Time zone
JavaScript gets this information from the user's computer.
It is only as accurate as the computer's date and time settings.
For example, if the user just moved from the U.S. West Coast to the U.S. East
Coast and hasn't reset the time zone on his computer, the computer will still be on
Pacific Time.
The Date object, too, will be on Pacific Time.
The Date object may resemble a string, but it isn't one.
For example, you can't use methods on it like
charAt, indexOf, or slice.
If you need the Date object to be a string, you can convert it to one the same way you
convert a number to a string.
Example:
var dateString = rightNow.toString();
The code above converts the Date object represented by the variable rightNow to a
string and assigns the string to the variable dateString.
Most of the time, you'll just want to extract some of the information from the Date object
without converting it to a string.
The following code creates a new Date object, assigns it to the variable rightNow,
extracts the day of the week, and assigns the day of the week to the variable theDay.
var rightNow = new Date();
var theDay = rightNow.getDay();
When you extract the day of the week from the object Object, it's represented as a
number.
Days are designated by a number from 0 for Sunday through 6 for
Saturday.
This means that you'll need a bit of code to convert it back into a day name like
"Mon."
33
Example:
var dayNames = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
var now = new Date();
var theDay = now.getDay();
var nameOfToday = dayNames[theDay];
Here's a summary of important methods for extracting pieces of the Date object.
getMonth() gives you not the spelled-out name of the month shown in the Date object,
but a number.
The following code produces a month number ranging from 0 for January through
11 for December.
var d = new Date();
var currentMonth = d.getMonth()
getDate gives you a number for the day of the month.
34
var dayOfMonth = d.getDate();
getFullYear gives you a 4-digit number for the year.
var currYr = d.getFullYear();
getHours gives you a number from 0 through 23 corresponding to midnight through 11
p.m.
var currentHrs = d.getHours();
getMinutes gives you a number from 0 through 59.
var currMins = d.getMinutes();
getSeconds gives you a number from 0 through 59.
var currSecs = d.getSeconds()
getMilliseconds gives you a number from 0 through 999.
var currMills = d.getMilliseconds();
getTime gives you the number of milliseconds that have elapsed since midnight, Jan. 1,
1970.
var millsSince = d.getTime();
Suppose you want to compute many days before the U.S. Social Security program goes broke.
The first step is to create a Date object for the current date and time:
1. var today = new Date();
Next, you create a second Date object.
But this time you specify the future date, June 30, 2035.
2. var doomsday = new Date("June 30, 2035");
Next, you extract from both dates the milliseconds that have elapsed since the reference
date of January 1, 1970.
3. var msToday = today.getTime();
4. var msDoomsday = doomsday.getTime();
You calculate the difference.
5. var msDiff = msDoomsday - msToday;
Some simple math converts the milliseconds to days.
6. var dDiff = msDiff / (1000 * 60 * 60 * 24);
35
The huge number created by the math inside the parentheses converts the milliseconds
into seconds (1000), minutes (60), hours (60), and days (24).
You want a number that represents whole days, so you round down.
The following statement rounds the number of days, which is probably a floating-point
number, down to an integer.
7. dDiff = Math.floor(dDiff);
The whole thing can be condensed into something that looks more like production code
1. var msDiff = new Date("June 30, 2035").getTime() - new Date().getTime();
2. var daysTillDoom = Math.floor(msDiff / (1000 * 60 * 60 * 24));
Line 1 subtracts the milliseconds since the reference date of the current moment from the
milliseconds since the reference date of June 30, 2035.
Line 2 converts the milliseconds to days and rounds down.
If the time is important, you can specify that as well.
var d = new Date("July 21, 1983 13:25:00");
Note the form used to specify the time:
No comma after the date. 24-hour time.
Colons separating hours, minutes, and seconds.
setFullYear sets the year of an existing Date object without changing any other element.
1. var d = new Date();
2. d.setFullYear(2001);
Line 1 creates a new Date object for the current moment.
36
Line 2 changes the year of the Date object to 2001, leaving all other elements of the Date
object intact.
setMonth sets the month of an existing Date object without changing any other element.
1. var d = new Date();
2. d.setMonth(11);
Line 1 creates a new Date object for the current moment.
Line 2 changes the month of the Date object to 11 (December), leaving all other elements
of the Date object intact.
setDate sets the day of the month of an existing Date object without changing any other
element.
1. var d = new Date();
2. d.setDate(15);
Line 1 creates a new Date object for the current moment.
Line 2 changes the date of the Date object to the 15th of the month, leaving all other
elements of the Date object intact.
setHours sets the hours of an existing Date object without changing any other element.
1. var d = new Date();
2. d.setHours(13);
Line 1 creates a new Date object for the current moment.
Line 2 changes the hours of the Date object to the 13th hour (1 p.m.), leaving all other
elements of the Date object intact.
setMinutes sets the minutes of an existing Date object without changing any other
element.
1. var d = new Date();
2. d.setMinutes(05);
Line 1 creates a new Date object for the current moment.
Line 2 changes the minutes of the Date object to 5 minutes after the hour, leaving all
other elements of the Date object intact.
setSeconds sets the seconds of an existing Date object without changing any other
element.
1. var d = new Date();
2. d.setSeconds(55);
Line 1 creates a new Date object for the current moment.
Line 2 changes the seconds of the Date object to the 55 seconds after the minute, leaving
all other elements of the Date object intact.
setMilliseconds sets the milliseconds of an existing Date object without changing any
other element.
1. var d = new Date();
2. d.setMilliseconds(867);
37
Line 1 creates a new Date object for the current moment.
Line 2 changes the milliseconds of the Date object to 867 milliseconds after the second,
leaving all other elements of the Date object intact.
JavaScript Events
38
Some of the events that are normally the result of some user actions are:
Event Meaning
onload Occurs when a window or frame has loaded
onunload Occurs when a document is removed from a window or frame
onclick The mouse is clicked on an element
ondblclick The double click event
onmousedown Mouse down event
onmouseup Mouse up event
onmouseover Mouse moves onto an element
onmousemove Mouse moves over an element
onmouseout Mouse leaves an element
onfocus Element receives focus
onblur Element loses focus
onkeypress Key press event
onkeydown Key is pressed down
onkeyup Key is released
onsubmit Submit button is pressed
onreset Form reset event occurs
onselect Some text in an element is selected
onchange Element loses focus and its value changes
Events: link
Here's a line that displays a link and then displays an alert when the user clicks it.
<a href="#" onClick="alert('Hi');">Click</a>
When the user clicks this link, it behaves differently than normal hyperlinks.
Instead of taking the user to another page, or to a named anchor on the same page, it
displays an alert
saying "Hi".
When the user clicks the link, it goes nowhere, and instead executes a JavaScript
statement, in this case calling a function.
When the user clicks the link, you don't want a new webpage to be loaded in this case, so,
instead of a URL, you place a # inside the quotation marks.
This tells the browser to reload the current page.
But there's a problem with the markup above.
<a href="#" tells the browser to reload the page.
39
This means that if the user has scrolled down to the link, the click, in addition to
running the JavaScript code, will scroll the page back to the top—an action you
don't normally want.
prefer this approach:
<a href="JavaScript:void(0)" onClick="alert('Hi');">Click</a>
Now the click executes only a single JavaScript statement.
But there is no limit to the number of JavaScript statements that you can enclose
in the quotation marks.
An example to show this principle is: with this example.
<a href="JavaScript:void(0)" onClick="var greet=’hi’; alert(greet);">Click</a>
Events: button
Suppose that when the user clicks a button, an alert displays saying, "Hello world!"
Here's the code.
<input type="button" value="Click" onClick="alert('Hello world!');">
The event handler is the same, whether you're coding a link or a button:
onClick="alert('Hello world!');"
But the beginning of the code is different:
<input type="button" value="Click" onClick="alert('Hello world!');">
Some people would argue that the button code should be enclosed in form tags, but it's
not absolutely necessary.
As an HTML coder you know that you can use an image as a hot link.
The markup would look something like this.
<a href="summary-page.html"><img src="button-sum-pg.png"></a>
You can also use an image to trigger an event.
Example:
<img src="button-greet.png" onClick="alert('Hello world!');"> Or,
if you want to be more professional about it, you could have the event trigger a
function.
<img src="button-greet.png" onClick="greetTheUser();">
Events: mouse
Events: fields
Suppose you have a text field for the user's email address.
When the user clicks in the field to type her entry, the field turns yellow.
This is the markup that makes it happen.
Email:<br>
<input type="text" size="30" onFocus="this.style.backgroundColor='yellow';">
The keyword here is onFocus.
It tells JavaScript to do something when the user clicks in the field.
This markup handles both the onFocus and the onBlur events.
Email:<br>
<input type="text" size="30" onFocus="this.style.backgroundColor='yellow';"
onBlur="this.style.backgroundColor='white';">
When the user clicks into the field, it turns yellow. When she clicks out of the
field, it reverts to white.
A slightly more professional approach would be to call functions that accomplish the
same things.
Email:<br>
41
<input type="text" size="30" onFocus="makeFieldYellow();"
onBlur="makeFieldWhite();">
Suppose you've included an email field in a form, and you've made it a required field.
The form has a submit button that the user clicks to submit the information that he's
entered in the form.
This is the markup that creates the form.
<form>
Email:
<input type="text">
<input type="submit" value="Submit">
</form>
The form markup has three elements:
1. The text "Email"
2. The text field for the user's email address
3. The submit button
The email field can be given an id as follows:
<form>
Email:
<input type="text" id="email">
<input type="submit" value="Submit">
</form>
Next, an event-handler can be added by using the keyword onSubmit:
<form onSubmit="checkAddress('email');">
Email:
<input type="text" id="email">
<input type="submit" value="Submit">
</form>
Now, when the user clicks the submit button, the function checkAddress executes.
Note that
even though the action is a click on the submit button, the onSubmit event
handler is in the form tag, not in the submit button tag.
That's because the submission is an event that applies to the whole form, not the
submit button.
When the form is submitted, the function checkAddress looks to see if the user has
entered anything in the email field.
If not, the function displays an alert reminding the user that the email address is required.
42
In order to do this, the function needs a way to read what's in the email field.
This is where the id that is added to the field comes in.
Here's the code for the function.
1. function checkAddress(fieldId) {
2. if (document.getElementById(fieldId).value == "") {
3. alert("Email address required.");
4. }
5. }
If there's no value in the email field, an alert displays telling the user that an email
address is required.
Some coders prefer to put the value found in the field into a variable, like this.
1. function checkAddress(fieldId) {
2. var val = document.getElementById(fieldId).value;
3. if val == "") {
4. alert("Email address required.");
5. }
6. }
Suppose the user has entered her ZIP code in a form field.
You want to save her the trouble of entering the city and state.
So when she clicks out of the field, you fill in the city field for her.
Assume there are only three ZIP codes in the U.S. and also that the user will infallibly
enter one of these codes.
For this example, the JavaScript code will fill in only the city
field, not the state.
Here's the relevant markup for the form:
ZIP:<br>
<input type="text" id="zip" onBlur="fillCity();"><br>
City:<br>
<input type="text" id="city">
</form>
When the user clicks out of the ZIP field, the onBlur event triggers the fillCity
function.
This is the code.
1. function fillCity() {
2. var cityName;
43
3. var zipEntered = document.getElementById("zip").value;
4. switch (zipEntered) {
5. case "60608" :
6. cityName = "Chicago";
7. break;
8. case "68114" :
9. cityName = "Omaha";
10. break;
11. case "53212" :
12. cityName = "Milwaukee";
13. }
14. document.getElementById("city").value = cityName;
15. }
This example shows that you can not only read a value in a field with
document.getElementById..., but can also "write" a value into a field.
In this case, the function assigns the value found in the ZIP field to a variable.
Then, using a switch statement, it matches the ZIP to a city name and assigns that name
to a second variable.
Then, using the variable, it places the city name in the city field.
Your webpage initially displays a picture of a little mammal known as the slow loris,
along with a single sentence:
Slow lorises are a group of several species of strepsirrhine primates which make
up the genus Nycticebus. Click for more.
When the user clicks the link, the paragraph expands:
Slow lorises are a group of several species of strepsirrhine primates which make
up the genus Nycticebus. They have a round head, narrow snout, large eyes, and a
variety of distinctive coloration patterns that are species-dependent. The hands
and feet of slow lorises have several adaptations that give them a pincer-like grip
and enable them to grasp branches for long periods of time. Slow lorises have a
toxic bite, a rare trait among mammals.
This is the markup.
<p id="slowLoris">
Slow lorises are a group of several species of strepsirrhine primates which make
up the genus Nycticebus.
<a href="javascript:void(0);" onClick="expandLoris();"><em>Click for
44
more.</em></a>
</p>
An id is assigned to the paragraph, which will be used by the function. When the user
clicks the link, a function, expandLoris, is called.
This is the function.
1. function expandLoris() {
2. var expandedParagraph = "Slow lorises are a group of several species of trepsirrhine
primates which make up the genus Nycticebus. They have a round head, narrow
snout, large eyes, and a variety of distinctive coloration patterns that are species
dependent. The hands and feet of slow lorises have several adaptations that give them
a pincer-like grip and enable them to grasp branches for long periods of time. Slow
lorises have a toxic bite, a rare trait among mammals.";
3. document.getElementById("slowLoris").innerHTML = expandedParagraph;
4. }
Line 2 assigns the long version of the text to a variable. Then, identifying the paragraph
by its id,
line 3 replaces the original content, the innerHTML, with the text stored in the variable.
Almost anything, including HTML tags, can be inserted into the web page this way.
For example, you could make this list appear on the page within, say, a div with the id
"lorisList".
1. Slow loris
2. Fast loris
3. Just-right loris
This is the function that loads the list markup into the div, which has been given an id of
"lorisList".
1. function placeAList() {
2. var listToPlace = "<ol><li>Slow loris</li><li>Fast loris</li><li>Just-right
loris</li></ol>";
3. document.getElementById("lorisList").innerHTML = listToPlace;
4. }
Line 2 assigns all the HTML for the list to a variable. Line 3 places the HTML into the
div that has been assigned the id "lorisList".
You can use document.getElementById(element id).innerHTML to read as well as
"write" the contents of an element.
For example, this function assigns whatever is in the paragraph, div, or other element
with the id "content" to the variable whatsThere.
1. function peekAtContent() {
2. var whatsThere = document.getElementById("content").innerHTML;
3. }
45
Line 2 reads all the HTML within the element with an id of "content" and assigns it to the
variable whatsThere.
If the element is, for example, a paragraph whose content is "
<em>Hello, Sailor!</em>" the variable whatsThere captures "<em>Hello, Sailor!</em>"
When the function is called, it assigns the "hidden" class to the element with the id
"ugly."
The image disappears.
Suppose you want to give your users the option of doubling the size of the text in all the
paragraphs of the document.
To accomplish this, you could give each paragraph an id.
When the user clicks the Double Text Size button, a function would cycle through all the
paragraph ids and make the change.
The function could upsize the font either by assigning a new class to each paragraph, with
the class specifying a larger font size, or it could assign the new style property directly,
like this:
getElementById(the id).style.fontSize = "2em";
46
An easier way to accomplish the same thing is to have the function say, "Find all the
paragraphs in the document and increase their size."
This statement finds all the paragraphs and assigns them to a variable:
var par = document.getElementsByTagName("p");
The variable, par, now holds an array-like collection of all the paragraphs in the
document.
Suppose that the body of the document comprises just three paragraphs.
<p>This bed is too small.</p>
<p>This bed is too big.</p>
<p>This bed is just right.</p>
par[0] is the first paragraph. par[1] is the second paragraph. par[2] is the third
paragraph.
par.length is 3, the number of items in the collection.
If you write...
var textInMiddleParagraph = par[1].innerHTML;
...the variable textInMiddleParagraph is assigned "This bed is too big."
If you write...
par[1].innerHTML = "This SUV is too big.";
...the paragraph text changes to "This SUV is too big."
Here's a loop that assigns a font family to all the paragraphs.
1. for (var i = 0; i < par.length; i++) {
2. par[i].style.fontFamily = "Verdana, Geneva, sans-serif";
This statement makes a collection of all the images in the document and assigns it to the
variable pics.
var pics = document.getElementsByTagName("img");
This statement makes a collection of all the divs in the document and assigns it to the
variable divs.
var divs = document.getElementsByTagName("div");
This statement makes a collection of all the unordered lists in the document and assigns it
to the variable ulists.
var ulists = document.getElementsByTagName("ul");
This statement makes a collection of all the paragraphs in the document and assigns the
collection to the variable pars.
var pars = document.getElementsByTagName("p");
47
This statement "reads" the contents of the second element in the collection pars and
assigns the string to the variable textInMiddleParagraph.
var textInMiddleParagraph = pars[1].innerHTML;
Suppose you don't want a collection of all the paragraphs in the document.
Suppose you want just a collection of all the paragraphs within a particular div. No
problem. Let's say the id of the div is "rules".
Here's the code:
1. var e = document.getElementByID("rules");
2. var paragraphs = e.getElementsByTagName("p");
48
Objects
An object is an entity characterized by its properties and behaviours. The properties are used to
define the data members of an object while the behaviours are used to manipulate the data
members.
Hosting Plans
Basic Professional Ultimate
Monthly $3.99 $5.99 $9.99
Disc Space 10GB 500GB 2000GB
Data Transfer 1000GB/Mo 5000GB/Mo 20000GB/Mo
Site Pages 10 50 500
If you wanted to use this data in JavaScript, you could assign each value to a different variable,
like this.
Having made all these variable assignments, you could then, for example, write this
JavaScript statement...
alert("The cost of the " + plan2Name + "package is $" + plan2Price + " per
month.");
...and an alert would display saying, "The cost of the Professional package is
$5.99 per month."
49
But assigning all these values to variables is unwieldy, and can lead to problems if things
get complicated.
A better way to handle the situation is to create objects with properties.
This is a handier scheme that more accurately reflects the 2-dimensional, gridlike nature
of the host company's table that we started with.
This table shows all the options expressed as objects and properties.
50
Things to notice:
The code begins like any variable definition, with the keyword var, followed by the
object name, and then an equal sign.
But then, instead of a value, there's a curly bracket, whose twin comes at the end of the
block.
Each property begins with a name, followed by a colon, and then a value.
Each property definition except the last ends with a comma.
The closing curly bracket is followed by a semicolon, because of the equal sign in the
first line.
If the current month is July, August, or December, the customer gets a 20 percent
discount on the hosting plan.
To keep track of those special months, we'll assign them to a new property.
This new property is an array, not a simple variable.
plan1.discountMonths = [6, 7, 11];
The statement above creates a new property of the object plan1, discountMonths, and
assigns an array to it representing the three months when the customer gets a discount.
You refer to the individual elements of this array property the same way you'd refer to the
elements of any array, with a number inside brackets, but using the dot notation of the
objectproperty pair, plan1.discountMonths.
var mo = plan1.discountMonths[2];
The statement above assigns the third element of the array, the number
representing December, to the variable mo.
So far, we've defined only one object, plan1, and its properties.
To complete the set of objects that includes plan2 and plan3, you'd have to do the same
thing again, and then again.
Objects:
Properties
To change the value of an object's number value, use a simple assignment statement, the
same way you'd assign a value to a plain variable.
deal3.cost = 79.95;
Whatever the value of deal3.cost was, now it's 79.95.
You can also assign a string instead of a number.
51
deal3.name = "Super-saver";
Whatever the value of deal3.name was, now it's "Super-saver".
You can also assign an array list to a property.
deal3.features = ["Guarantee", "Free Ship"];
Whatever the value of deal3.features was, now it's an array with the elements
"Guarantee" and "Free Ship."
You can also assign a Boolean value.
deal3.membersOnly = false;
Whatever the value of deal3.membersOnly was, now it's false.
You can also use an assignment statement to define a new property for an object.
Suppose the object deal3 has some properties, but none of them are deal3.market.
Now you want to add it, while assigning it a value.
deal3.market = "regional";
Just as you can create an undefined variable by not assigning it a value, you can create an
object without any properties.
var deal4 = {};
If you want to create a property now and assign it a value later, you can create it with a
value of undefined.
deal3.market = undefined;
Note that the keyword undefined isn't in quotation marks.
o It isn't a string.
Things to notice:
52
Objects:
Methods
Consider the following chart showing different hosting plans.
Hosting Plans
Basic Professional Ultimate
Monthly $3.99 $5.99 $9.99
Disc Space 10GB 500GB 2000GB
Data Transfer 1000GB/Mo 5000GB/Mo 20000GB/Mo
Site Pages 10 50 500
Discount Mo Jul, Aug Jul, Aug, Dec Jul, Aug
We're going to write a function that calculates the annual charge based on this chart.
Note that if the user signs up at certain times of the year, he gets a discount for the entire
year.
If he signs up for the Basic plan in July or August, he gets 20 per cent off.
If he signs up for the Professional plan in July, August, or December, he gets 20 per cent
off.
If he signs up for the Ultimate plan in July or August, he gets 20 per cent off.
We begin by creating three objects with properties.
This is the object and its properties that represent the Basic plan.
1. var plan1 = {
2. name: "Basic",
3. price: 3.99,
4. space: 100,
5. transfer: 1000,
6. pages: 10,
7. discountMonths: [6, 7]
8. };
The function below cycles through all the discount months (line 5) checking to see if any
of them happen to be the current month (line 6).
If so, it calculates a 20 percent discount by multiplying the regular price by .8.
Then it multiplies the monthly price, discounted or not, by 12, to get the
annual price, and returns the number to the calling code (line 11).
1. function calcAnnual() {
2. var bestPrice = plan1.price;
3. var currDate = new Date();
53
4. var thisMo = currDate.getMonth();
5. for (var i = 0; i < plan1.discountMonths.length; i++) {
6. if (plan1.discountMonths[i] === thisMo) {
7. bestPrice = plan1.price * .8;
8. break;
9. }
10. }
11. return bestPrice * 12;
12. }
This is the calling statement that passes the value to the function and executes it.
In this example, it passes the value .85, representing a discount of 15 percent.
var annual Price = calcAnnual(.85);
As you can attach a variable to an object, and the variable becomes the object's property.
You can also attach a function to an object, and the function becomes that object's
method.
The method does the same task the regular function does, but now it's
attached to an object.
The code below inserts the function coded above into the object definition, so now it's a
method.
1. var plan1 = {
54
2. name: "Basic",
3. price: 3.99,
4. space: 100,
5. transfer: 1000,
6. pages: 10,
7. discountMonths: [6, 7],
8. calcAnnual: function(percentIfDisc) {
9. var bestPrice = plan1.price;
10. var currDate = new Date();
11. var thisMo = currDate.getMonth();
12. for (var i = 0; i < plan1.discountMonths.length; i++) {
13. if (plan1.discountMonths[i] == thisMo) {
14. bestPrice = plan1.price * percentIfDisc;
15. break;
16. }
17. }
18. return bestPrice * 12;
19. }
20. };
Things to notice:
Except for the first line, every line of the method is identical to the code used to create
the plain function that we started with.
The method definition begins the same way a property definition begins, with the name
followed by a colon.
A comma ends every property definition and method definition except for the last
property or method.
If you were to add a property or method below the calcAnnual method definition, you'd
need to insert a comma after the closing curly bracket of the calcAnnual definition.
The parentheses that indicate that a variable name is the name of a function come
immediately after the keyword function.
Parameters, if there are any, go inside the parens, as in any function definition.
This is how you'd call the method.
var annualPrice = plan1.calcAnnual(.85);
In the method definition coded above, the properties are referred to using the name of the
object—for example, plan1.price.
55
This works, but a better approach, is to replace the name of the object with the keyword
this.
When JavaScript sees this keyword, it knows you're referring to the object that's being
defined.
1. var plan1 = {
2. name: "Basic",
3. price: 3.99,
4. space: 100,
5. transfer: 1000,
6. pages: 10,
7. discountMonths: [6, 7],
8. calcAnnual: function(percentIfDisc) {
9. var bestPrice = this.price;
10. var currDate = new Date();
11. var thisMo = currDate.getMonth();
12. for (var i = 0; i < this.discountMonths.length; i++) {
13. if (this.discountMonths[i] === thisMo) {
14. bestPrice = this.price * percentIfDisc;
15. break;
16. }
17. }
18. return bestPrice * 12;
19. }
20. };
When you write this.whatever, JavaScript is smart enough to understand that you're
referring to a property of the object that's being defined—in this case, plan1.
Objects:
Constructors
Consider a version of the chart showing different hosting plans.
Hosting Plans
Basic Professional Ultimate
Monthly $3.99 $5.99 $9.99
Disc Space 10GB 500GB 2000GB
Data Transfer 1000GB/Mo 5000GB/Mo 20000GB/Mo
Site Pages 10 50 500
56
This is how the information for the Basic plan is encapsulated in an object and five
properties.
1. var plan1 = {
2. name: "Basic",
3. price: 3.99,
4. space: 100,
5. transfer: 1000,
6. pages: 10
7. };
But that only gets us an object that represents the first plan.
We would have to do the same thing again for the Professional and Ultimate plans.
This is too much hand craftsmanship.
In order to reduce too much work, JavaScript lets us build the objects using a constructor
function as follows:
1. function Plan(name, price, space, transfer, pages) {
2. this.name = name;
3. this.price = price;
4. this.space = space;
5. this.transfer = transfer;
6. this.pages = pages;
7. }
This would be like a plain function definition but for two differences:
1. The function name is capitalized.
JavaScript doesn't care whether you do this or not, but it's conventional to do it to
distinguish constructor functions from regular functions.
2. Each of the parameter values is assigned to a variable.
But the variable is a property attached to some object whose name hasn't been
specified yet.
Just as the parameter values will be filled in by the calling code, so will the name
of the object.
This is the calling code that creates the object for the Basic plan.
var plan1 = new Plan("Basic", 3.99, 100, 1000, 10);
This would be just a regular function call if it weren't for that new.
It's the keyword that tells JavaScript to create a new object.
The name of the new object is plan1.
Its properties are enumerated inside the parentheses.
57
Now it's easy to mass-produce as many objects as you want, using the same pattern.
1. var plan1 = new Plan("Basic", 3.99, 100, 1000, 10);
2. var plan2 = new Plan("Premium", 5.99, 500, 5000, 50);
3. var plan3 = new Plan("Ultimate", 9.99, 2000, 20000, 500);
It's common to use the same names for parameters and properties, but you don't have to.
You could write:
1. function Plan(name, price, space, transfer, pages) {
2. this.doc = name;
3. this.grumpy = price;
4. this.sleepy = space;
5. this.bashful = transfer;
6. this.sneezy = pages;
7. }
Objects:
Constructors for methods
Consider the version of the hosting chart that includes discount months.
Hosting Plans
Basic Professional Ultimate
Monthly $3.99 $5.99 $9.99
Disc Space 10GB 500GB 2000GB
Data Transfer 1000GB/Mo 5000GB/Mo 20000GB/Mo
Site Pages 10 50 500
Discount Mo Jul, Aug Jul, Aug, Dec Jul, Aug
When you attach a variable to an object, it's called a property of the object.
When you attach a function to an object, it's called a method of the object.
In the example below, the method checks to see if the current date is in a discount
month and, if so, applies the discount.
Then the method calculates the annual charge.
If you're creating more than one object with the same pattern of properties and methods,
it's a convenience to build the method as well as the properties into the
constructor function.
In the following code, the constructor creates the same method for every object that is
created, as it creates all the properties for each object.
1. function Plan(name, price, space, transfer, pages, discountMonths) {
58
2. this.name = name;
3. this.price = price;
4. this.space = space;
5. this.transfer = transfer;
6. this.pages = pages;
7. this.discountMonths = discountMonths;
8. this.calcAnnual = function(percentIfDisc) {
9. var bestPrice = this.price;
10. var currDate = new Date();
11. var thisMo = currDate.getMonth();
12. for (var i = 0; i < this.discountMonths.length; i++) {
13. if (this.discountMonths[i] === thisMo) {
14. bestPrice = this.price * percentIfDisc;
15. break;
16. }
17. }
18. return bestPrice * 12;
19. };
20. }
59
Once the objects and their properties and method are created by the code above, this is
the code that calls, for example, the method for the Premium plan.
var annualPrice = p2.calAnnual(.85);
The main difference between the method definition in the one-off literal object definition
(no constructor) and the method definition in the constructor function is the first line.
In other respects, both definitions are identical.
This is the first line of a method definition when an object is created on a one-off basis
without a constructor:
calcAnnual: function(percentIfDisc) {
This is the first line of a method definition within a constructor:
this.calcAnnual = function(percentIfDisc) {
There are two other differences.
Because in the constructor function the method definition
begins with an assignment (something = something else), you need a semicolon
after the closing curly bracket.
And no comma is necessary if another property or method definition follows.
Objects:
Prototypes
Consider a chart showing the three objects and their properties and method.
Hosting Plans
Object plan1 plan2 plan3
name (a property) “Basic” “Professional” “Ultimate”
price (a property) 3.99 5.99 9.99
space (a property) 100 500 2000
transfer (a property) 1000 5000 20000
pages (a property) 10 50 500
discountMonths (a property) Jul, Aug Jul, Aug, Dec Jul, Aug
calcAnnual (a method) Calculates Calculates Calculates
annual charge annual charge annual charge
60
Each object corresponded to a hosting plan.
Each object had six properties and one method.
The properties shown in the rows above are customized for each object, but the method is
always the same from object to object.
The constructor function keeps duplicating the same method for each object, object
after object.
If we were to create 100 objects using the constructor, JavaScript would duplicate the
same method 100 times, once for each object.
It would work, but it is not pretty.
The table below, which shows all of the objects sharing a single method, makes more
sense.
We want only one copy of the method, shared by all objects created with the constructor,
no matter how many objects are created.
This achieved with the use of a prototype statement.
First, we don't include the method in the constructor function, because that creates a copy
of the method for every single object that's created with the constructor.
Instead, we define the method as a prototype of the constructor as follows:
1. Plan.prototype.calcAnnual = function(percentIfDisc) {
2. var bestPrice = this.price;
3. var currDate = new Date();
4. var thisMo = currDate.getMonth();
5. for (var i = 0; i < this.discountMonths.length; i++) {
6. if (this.discountMonths[i] === thisMo) {
7. bestPrice = this.price * percentIfDisc;
8. break;
9. }
10. }
61
11. return bestPrice * 12;
12. };
Now, all objects created with the constructor Plan will share the same copy of the
method calcAnnual.
There's no unnecessary duplication.
Note that except for the first line, the method is coded exactly as when it was
part of the constructor definition.
Even the first line is the same, if you consider only the parts on the right side of the equal
sign.
The parts on the left side, connected by dots, are:
the name of the constructor function, in this case Plan the keyword prototype
the name of the method that all objects created with Plan will share, in this case
calcAnnual
This is how the object table looks with the prototype method and the prototype property.
62
You achieve this by using the statement:
plan1.cancellable = false;
All objects created with the constructor still share the property cancellable, but now
the value of that property for one object is different from all the others.
Objects:
Checking for properties and methods
You can check to see if an object has a particular property by writing a simple statement
like this:
var gotTheProperty = "price" in plan1;
Here are the parts:
the property in question, enclosed in quotes—in this case, price the keyword in
the object, in this case, plan1
Again, the question is, does the object named plan1 have a property called price?
In other words, is there such a thing as plan1.price?
In the example of three hosting plans that we've been using, plan1 does have a price,
3.99.
So gotTheProperty is assigned true.
But plan1 doesn't have a property named location.
So if we write...
var gotTheProperty = "location" in plan1;
...the variable gotTheProperty is false.
plan1 in the example also has a method named calcAnnual.
A method is a type of property of an object, so if you write...
63
var gotTheProperty = "calcAnnual" in plan1;
...the variable gotTheProperty is true.
Things to notice:
The property, a variable, is enclosed in quotation marks.
We're not used to putting JavaScript variables inside quotation marks, so this is
something to make a note of.
The keyword is in—pretty intuitive.
o The code asks, "Is there a property called 'price' in plan1?"
If you want a list of an object's properties, you use the following code:
1. var listOfProperties = [];
2. for (var prop in plan1) {
3. listOfProperties.push(prop);
4. }
Browser control:
Getting and setting the URL
In addition to making things happen on the webpage, you can use JavaScript to control
the browser.
You can get the browser to tell you its current location using the statement:
var whereWeAt = window.location.href;
For example, if the browser is currently at
http://www.mybeautifulsite.com/products/page33.html#humidifier,
the statement above will assign the string
"http://www.mybeautifulsite.com/products/page33.html#humidifier"
to the variable whereWeAt.
You can also get pieces of this.
This statement gets just the domain name.
var theDomain = window.location.hostname;
In the example, the string "www.mybeautifulwebsite.com" is assigned to the variable
theDomain.
"http://", the path, and the anchor are omitted.
You get the path as follows:
var thePath = window.location.pathname;
In the example, the string "/products/page33.html" is assigned to the variable thePath.
If the browser were on the home page and the URL were simply
http://www.mybeautifulsite.com, the string "/" would be assigned to the variable.
In the example, the browser has been pointed to a section of the page marked by the
anchor #humidifier.
This statement identifies the anchor.
var theAnchor = window.location.hash;
The string "#humidifier" is assigned to the variable theAnchor.
If there is no anchor in the URL, the variable is assigned an empty string, "".
As usual, you can reverse the order of things, telling the browser where to go instead of
asking where it is using the statement:
65
window.location.href = "http://www.me.com/1.html";
The statement above tells the browser to navigate to the page named 1.html at the site
me.com.
If you wanted the browser to navigate to the site's home page, you'd write...
window.location.href = "http://www.me.com";
And if you wanted it to land on an anchor...
window.location.href = "http://www.me.com/1.html#section9";
It would be nice if you could use window.pathname = ... to move to a different page
on the current site or window.hash = ... to move to an anchor on the current page, but you
can't.
What you can do, though, is query the browser for the domain name and combine that
with the page where you want to go using the following code:
1. var currentSite = window.location.hostname;
2. var destination = "http://" + currentSite + "/wow.html";
3. window.location.href = destination;
66
Coding alternatives to be aware of:
Browser control:
Getting and setting the URL another way
You can direct the browser to a new URL by using the following statement
window.location.assign("http://www.me.com");
The statement directs the browser to the home page of me.com.
As with the window.location.href statement, you can make the URL as detailed as you
like.
window.location.assign("http://www.me.com/lojack.html#guarantee");
The statement directs the browser to the anchor #guarantee on the lojack.html
page of the site me.com.
Here's another alternative that has a slightly different effect.
window.location.replace("http://www.me.com/lojack.html#guarantee");
Once again, the statement directs the browser to a new URL.
But by using replace instead of assign, you interfere with the browser history.
When you use assign, the history is intact.
The statement takes the user away from the original page, to the new page.
If, after arriving at the new page, she presses the Backspace key or clicks the
browser's back button, she goes back to the original page that she just came from.
But when you use replace, the original page doesn't make it into the history.
If the user presses Backspace after being taken to the new page, she's taken to the
page that displayed before the original page since the original page is no longer in
the history.
If there is no page before the original page, nothing happens when she presses
Backspace.
To reload the current page code one of these statements:
window.location.reload(true);
window.location.reload(false);
window.location.reload();
67
All three statements reload the current page.
If the argument is true (example 1 above), the statement forces the browser to
load the page from the server.
If the argument is false (example 2) or if there is no argument (example 3), the
browser will load the page from the cache if the page has been cached.
Browser control:
Forward and reverse
You can make the browser go back one URL in the browser history, as if the user has
pressed the Backspace key or clicked the browser's back button.
Use the statement: history.back();
To make the browser go forward in the history, as if the user has pressed alt-right-arrow
or clicked the browser's forward button...
Use the statement: history.forward();
In both cases, if there is no URL in the history that would make the move possible, the
browser does nothing.
You can tell the browser how many steps in the history you want to take, using negative
numbers to go back and positive numbers to go forward.
The following statement is the equivalent of pressing the Backspace key three times.
history.go(-3);
The following statement sends the browser forward two URLs.
history.go(2);
If a negative number inside the parentheses is greater than the number of previous URLs
in the history, the browser will do nothing.
If a positive number inside the parentheses is greater than the number of forward URLs in
the history, the browser will do nothing.
When you want to go forward or backward just one step, you can choose either method..
history.back(); or
history.go(-1);
And...
history.forward(); or
history.go(1);
68
There is no reliable way to find out how many items, backward and forward, there are in
the history.
If the user clicked a link to get to the current page, you can get the URL of the page
where the link was clicked.
var whereUserCameFrom = document.referrer;
The statement above assigns the URL where the link was clicked to the variable
whereUserCameFrom.
However, this works only if a link was clicked, including a link in a search result.
If the user got to your page through a bookmark or by entering your URL in the
address bar, the result of document.referrer will be an empty string, "".
Browser control:
a) You can use the write method to put HTML content on the screen
1. var monkeyWindow = window.open();
2. var windowContent = "<h1>Capuchin monkey</h1><img src= 'monkey.jpg'><p>The
word capuchin derives from a
group of friars<br>named the Order of Friars Minor Capuchin who wear<br>brown
robes with large hoods covering their heads.</p>";
3. monkeyWindow.document.write(windowContent);
69
Things to notice:
Inside the main quotes that enclose the whole string, any quoted text must be in single
quotes, as in <img src='monkey.jpg'>.
Using the document.write method, you place the HTML string on the page.
You designate the window by its handle, the variable that you declared when you opened
the window.
The document.write method in this example is used to fill an empty window with content.
You could also use it to write to a window that already has content.
But it will overwrite all the HTML of the original document, replacing its content
entirely.
Instead of assigning the HTML string to a variable and specifying the variable inside the
parentheses, you could just put the HTML string inside the parentheses, enclosed in
quotes of course.
But this would be even more unwieldy than the example code.
b) The second way to fill the window with content is to assign a document to it
monkeyWindow.location.assign("http://www.animals.com/capuchin.html");
...or...
monkeyWindow.location.href = "http://www.animals.com/capuchin.html";
c) The third and most common way to fill the window with content is to include the
document assignment in the statement that opens the window.
var monkeyWindow = window.open("http://www.animals.com/capuchin.html");
If the document you're opening in the popup shares the same host and directory as the
original document, you can just write...
var monkeyWindow = window.open("capuchin.html");
This is how you close a window.
monkeyWindow.close();
Browser control:
Controlling the window's size and location
70
The name is useful for specifying the target attribute of an <a> or <form> element in
HTML.
Things to know:
Things to know:
Both parameters, width and height, are enclosed by a single set of quotation marks.
The absence of spaces within the quotation marks isn't a mere style preference but a
requirement.
Any spaces here will break JavaScript.
The numbers refer to pixels.
In the example above, the window will be 420 pixels wide and 380 pixels high.
Width and height must be a minimum of 100.
Unlike the URL and name parameters, the order doesn't matter.
Width can come before height, height can come before width.
But the width-and-height set must come third, after URL and name.
In order to specify these parameters, you must specify a URL and name, even if
you specify empty strings.
A window that's smaller than the screen will display in the upper-left corner of the
screen.
But you can optionally tell the browser where to place the window.
var w = window.open("", "", "width=420,height=380,left=200,top=100");
71
Things to know:
The numbers are pixels—number of pixels from the left edge of the screen and
number of pixels from the top of the screen.
The positioning parameters are included within the same set of quotation marks as the
size parameters, and, like the size parameters, are separated by a comma and no space.
The parameter order within the quotation marks doesn't matter.
You can specify window size without specifying window position,
but if you specify window position without size,
it will be ignored since it will be a full-size window that fills the whole screen.
Some or all of the parameters can be assigned to a variable, and the variable
can be used in the statement that opens the window.
Since the whole thing has to be a quoted string, the quotes within the string have to be
changed to single quotes.
1. var windowSpecs = "'faq.html', 'faq', 'width=420,height=380,left=200,top=100'";
2. var faqPage = window.open(windowSpecs);
Browser control:
Testing for popup blockers
Popup blockers are now a standard feature of browsers, with some level of popup
blocking usually built in as a default.
JavaScript popups, and especially those that open a new page within the same website,
are often tolerated by default, but you can never be sure.
If popups are an essential feature of your site, you need to test whether your popups are
going to be blocked.
If they are, you can ask the user to disable the popup blocker for your site.
The test is pretty inelegant.
You attempt to open a small test popup, then quickly close it - so fast that the user may
not notice the little screen flash.
If the attempt succeeds, the window's handle will have a value.
If the popup is blocked, the handle will be null, and you can deliver your message to the
user.
Here's the code.
1. function checkForPopBlocker() {
2. var testPop = window.open("", "","width=100,height=100");
3. if (testPop === null) {
4. alert("Please disable your popup blocker.");
5. }
72
6. testPop.close();
7. }
The function shown above works with all browsers except Internet Explorer.
In Internet Explorer, if the popup is blocked, the handle will be undefined instead of null.
So to cover all bases, you need to code the function this way.
1. function checkForPopBlocker() {
2. var testPop = window.open("", "","width=100,height=100");
3. if (testPop === null || typeof(testPop === "undefined") {
4. alert("Please disable your popup blocker.");
5. }
6. testPop.close();
7. }
JavaScript helps you find out if the user is filling out your forms correctly
that is, helps you validate your form.
With form validation, if there's a problem, you can ask the user to try
again.
To begin with, if you have a required field, you can check to see if the user has entered
something in it.
Let's start with a simple form that asks the user to enter her last name.
Here's some markup for the form:
<form onSubmit="return checkForLastName();">
Please enter your last name.<br>
73
<input type="text" id="lastNameField">
<input type="submit" value="Submit Form">
</form>
When the user clicks the Submit button, the function checkForLastName is called.
Here's the function.
1. function checkForLastName() {
2. if (document.getElementById("lastNameField").value.length == 0) {
3. alert("Please enter your last name");
4. return false;
5. }
6. }
Line 2 asks whether the length of the value found in the field with the id "lastNameField"
is 0.
That is, is nothing entered there?
If so, an alert displays asking the user to enter her name.
And then in line 4 something else happens.
The Boolean value false is returned to the calling code.
This prevents the form from being submitted.
In order for the submission to be called off, there has to be a matching keyword return in
the markup that calls the function.
Without this return in the calling code, the return in line 4 of the function won't
stop the form from being submitted.
<form onSubmit="return checkForLastName();">
As a user-friendly touch, you can use the focus method to place the cursor in the field
that needs to be completed.
1. function checkForLastName() {
2. if (document.getElementById("lastNameField").value.length === 0) {
3. alert("Please enter your last name");
4. document.getElementById("lastNameField").focus();
5. return false;
6. }
7. }
74
1 function checkForLastName() {
2 var targetField = document.getElementById("lastNameField");
3 if (targetField.value.length === 0) {
4 alert("Please enter your last name");
5 targetField.focus();
6 return false;
7}
8}
The sample code in this chapter targets forms and fields by ID, which is the most
straightforward approach.
But you could target by name, by tag, or by position in the DOM hierarchy.
Instead of hard-wiring the ID into the function, you could potentially make it multi-use
by naming the field ID as a parameter, and passing the ID to it from the calling code.
75
Form validation: drop-downs
In the function, if selectedIndex is 0 (line 2), it means the user hasn't made a selection.
Line 3 displays an alert asking her to select.
Line 4 returns false, cancelling the form submission.
76
Here's the function, revised two ways.
First, it accepts the element ID as a parameter, allowing it to process more than one form.
Second, the element is assigned to a variable.
1. function checkForSelection(selecID) {
2. var target = document.getElementById(selecID);
3. if (target.selectedIndex === 0) {
4. alert("Please select a state.");
5. return false;
6. }
7. }
The function coded above needs the event-handler to include the ID as an argument.
<form onSubmit="return checkForSelection('states');">
Note that the radio buttons all have the same name, "r1".
This is the validating function that checks to see if the user has clicked one of the buttons.
1. function validateRadios() {
2. var radios = document.getElementsByName("r1");
3. for (var i = 0; i < radios.length; i++) {
4. if (radios[i].checked) {
5. return true;
6. }
7. }
8. alert("Please check one.");
9. return false;
10. }
77
Line 2 makes a collection of all the buttons with the name "r2" and assigns the collection
to the variable radios.
This is possible because, though an element can't share its id with any
other elements, any number of elements can share the same name.
Lines 3 and 7 loop through collection to see whether any of the buttons is checked.
If so, the code breaks out of the function with the return keyword in line 5,
passing back the Boolean true so the form can be submitted.
If the loop runs its course without finding any buttons checked, line 8 displays an
alert and line 9 returns false, cancelling the form submission.
The function can be used to validate button sections for any number of forms if we
specify a parameter, allowing the event-handler to pass the button group name to the
function.
1. function validateRadios(ename) {
2. var radios = document.getElementsByName(eName);
In order to use the function coded above, the event-handler would have to include the
button group name as an argument.
<form onSubmit="return validateRadios('r1');">
Let us consider a one-field form that asks the user to enter her ZIP code.
You need to test whether she's entered the right number of digits for a ZIP - n5 digits.
HTML gives you a way to keep her from entering too many digits: maxlength = 5.
But if you want to make sure she hasn't entered too few digits, you need to use
JavaScript.
Here's the function.
1. function validateZIP() {
2. var numChars = document.getElementById("zip").value.length;
3. if (numChars < 5) {
4. alert("Please enter a 5-digit code.");
5. return false;
6. }
7. }
If the number of characters in the field is fewer than 5, an alert displays and false is
returned to the calling code, cancelling the form submission.
Another question to ask about the ZIP field entry is whether the user has entered only
numbers.
78
Here's the additional code for that.
1. function validateZIP() {
2. var valueEntered = document.getElementById("zip").value;
3. var numChars = valueEntered.length;
4. if (numChars < 5) {
5. alert("Please enter a 5-digit code.");
6. return false;
7. }
8. for (var i = 0; i <= 4; i++) {
9. var thisChar = parseInt(valueEntered[i]);
10. if (isNaN(thisChar)) {
11. alert("Please enter only numbers.");
12. return false;
13. }
14. }
15. }
The highlighted code loops through the five characters that have been entered, checking
to make sure that all the characters are string characters representing numbers.
Because the five characters in the field are string characters, each one has to be converted
to a number if possible before being tested.
Line 9 does this.
Line 10 tests to see whether the attempted conversion worked.
If a number resulted from parseInt in line 9, no problem.
But if the character isn't a number after the conversion attempt - if it isNaN in line
10 - an alert displays and false is returned, cancelling the form submission.
Validating an email field includes checking to make sure there are no illegal characters,
like spaces, and that all the essentials of a legal email address are there: one or more
characters, followed by @, followed by one or more characters, followed by a dot,
followed by two to four characters.
The standard way to test for all this is to match the user's entry with
a regular expression.
Meanwhile, here's how to head off many user errors by using indexOf.
Let's start by checking for spaces, which are illegal in an email address.
79
1. function validateEmail() {
2. var eEntered = document.getElementById("email").value;
3. if (eEntered.indexOf(" ") !== -1) {
4. alert("No spaces allowed in address");
5. return false;
6. }
7. }
80
About line 7:
The first part, left of the pipes, tests whether the character is at the beginning of the
address, which would be illegal.
The second part, right of the pipes, tests whether there are fewer than 4 characters
following the character.
Since there must be at least one character for the domain name plus a dot plus at least two
characters for the extension, fewer than 4 characters following the @ would be illegal.
Finally, we will add a test for the dot that needs to be at least 1 character away from the
"@" and have 2 to 4 characters following it.
1. function validateEmail() {
2. var addressIsLegal = true;
3. var eEntered = document.getElementById("address").value;
4. if (eEntered.indexOf(" ") !== -1) {
5. addressIsLegal = false;
6. }
7. if (eEntered.indexOf("@") < 1 || eEntered.indexOf("@") > eEntered.length - 5) {>
8. addressIsLegal = false;
9. }
10. if (eEntered.indexOf(".") - eEntered.indexOf("@") < 2 || eEntered.indexOf(".") >
eEntered.length - 3) {
11. addressIsLegal = false;
12. }
13. if (addressIsLegal === false) {
14. alert("Please correct email address");
15. return false;
16. }
17. }
Line 10:
There must be at least one character between the dot and the @.
The first part, left of the pipes, tests whether that one character (or more) is missing,
which would be illegal.
There must also be at least 2 characters following the dot.
The second part, right of the pipes, tests whether there are fewer than 2 characters
following the character, which would be illegal.
81