What We Will Cover
Elucidations
Homework Questions?
Homework Discussion Questions
- What do you code to write the following text to a document?
<img src='imgNumber.jpg' alt='' />
- How do we fix the errors in the file: debugger.html?
^ top
5.1: Events and Event Handlers
Learner Outcomes
At the end of the lesson the student will be able to:
- Work with event handlers
- Insert a value into a Web form field
|
^ top
5.1.1: Case Study: New Year's Bash
- We are going to start this lesson by learning about event handlers
- To help us learn, the textbook presents a case study on page JVS 49
- You can see the design of the web site here: Dixon's New Year's Bash
- Hector's vision for Web site is a clock that updates itself every second
- We are going to create functions that will:
- Calculate current date and time
- Calculate time remaining until New Year's Day
- Run once every second
- We will run the function once every second
- The following image shows where we will display these values
New Year's Bash Form

^ top
5.1.2: Inserting Values into a Form
Creating the NYClock Function
- To update the fields, we create a function named
NYClock()
- This function updates all the fields of the
clockForm form
- At first we just insert placeholder values
- Later we will add current date and time values
- This function is shown in the following image from page JVS 52 of the textbook

^ top
5.1.3: Understanding Event Handlers
- To make the form update correctly, we need to use event handlers
- Some terms and definitions:
- Event: Action that occurs within a Web browser
- Event handler: Statement that tells browsers what code to run in response to specified event
- Most objects have specific events associated with them
- For example, a form button has an event that occurs when the button is clicked
- Another even event occurs when the mouse hovers over a button without clicking it
- By detecting and coding events, we can program a response in JavaScript
- The textbook lists some of the JavaScript event handlers on page JVS 54
- As you can see, the event handlers all start with the letters "
on"
Coding an Event Handler
Running JavaScript When the Page is Loaded
^ top
5.1.4: Running JavaScript Commands as Links
^ top
5.1.5: Summary
Check Yourself
- What is an event handler?
- What code would you write to insert the value "Friday" into a form named "weekdays" and a field named "today"?
- What attribute would you add to a button element to run the
showImage() function when the button is clicked?
- What HTML code would you write to create a link that runs the
showImage() function when the link is clicked?
^ top
Activity 5.1
Take one minute to read over the following Quick Quiz questions. We will discuss the questions in one minute.
Quick Quiz
^ top
5.2: Dates and the Date Object
Learner Outcomes
At the end of the lesson the student will be able to:
- Create and work with date objects
- Extract information from date objects
|
^ top
5.2.1: Working with Dates
- We have a function
NYClock() but we need some way to generate the date and time information automatically
- JavaScript has a
Date object that contains information about a specific date and time
- You create date objects with the following syntax:
objName = new Date("month day, year hours:minutes:seconds");
- For example:
sep18 = new Date("September 18, 2006 12:34:56");
- If you omit the time information, then JavaScript defaults to midnight of the specified day ("
00:00:00")
- If you omit both the date and time, then JavaScript returns the current date and time:
dateNow = new Date();
How Dates are Stored
- You may wonder how the
Date object stores the current date and time
- Internally, it stores the number of milliseconds since January 1, 1970
- A millisecond is
0.0001 seconds
^ top
5.2.2: Retrieving Date and Time Values
- A
Date object is the numeric value of the current date and time
- However, we want to work with only part of the Date, such as the day of the month
- To extract the information we want, we need to work with the methods of
Date
Retrieving the Day of the Month
Retrieving the Month
Retrieving the Year
Retrieving the Hour, Minute, and Second Values
- To get the current hour, minute, and second values from a
Date object, you use the syntax:
dateObject.getHours()
dateObject.getMinutes()
dateObject.getSeconds()
- For example:
<script type="text/javascript">
var dateNow = new Date();
var hours = dateNow.getHours();
var minutes = dateNow.getMinutes();
var seconds = dateNow.getSeconds();
var time = hours + ":" + minutes + ":" + seconds;
document.write("Time=" + time);
</script>
- Produces the following output:
Retrieving the Time Value
^ top
5.2.3: Setting Date and Time Values
More Information
^ top
5.2.4: Creating Date and Time Formatting Functions
- Now that we know how to get date and time values, we can use these methods in a function
- We will create two functions:
showDate() and showTime()
- Note that there are some small formatting issues with the time display
- We will learn techniques for handling this later in the lesson
Function showDate()
1
2
3
4
5
6
|
function showDate(dateObj) {
monthDay = dateObj.getDate();
month = dateObj.getMonth() + 1;
year = dateObj.getFullYear();
return month + "/" + monthDay + "/" + year;
}
|
Function showTime()
1
2
3
4
5
6
7
8
|
function showTime(dateObj) {
var hours = dateObj.getHours();
var minutes = dateObj.getMinutes();
var seconds = dateObj.getSeconds();
return hours + ":" + minutes + ":"
+ seconds;
}
|
^ top
5.2.5: Calling the Date and Time Functions
- Now that we have the date and time functions, we need to use in the web page for Dixon's New Year's Bash
- We update the
NYClock() function to make use of these date and time functions
- This update is shown in the image below taken from the textbook on page JVS 61
NYClock() Function Calling showDate() and showTime()

^ top
5.2.6: Summary
Check Yourself
- What JavaScript code would you use to create a variable named
examDate storing the date and time: November 13, 2006 at 18:05:24 P.M.?
- What command would you use to extract the month value from the
examDate variable? What value would be returned by this method?
- What command would you use to extract the 4-digit year value from the
examDate variable?
- What command would you use to change the day of the month value in the examDate variable from 8 to 9 (while leaving all of the other date and time values the same)?
- What command would you use to create a variable named currentTime that stores the current date and time (whatever that may be)?
^ top
Activity 5.2
Take one minute to read over the following Quick Quiz questions. We will discuss the questions in one minute.
Quick Quiz
^ top
5.3: Arithmetic and Assignment operators
Learner Outcomes
At the end of the lesson the student will be able to:
- Work with arithmetic operators to construct expressions
- Use assignment operators to assign values to variables
|
^ top
5.3.1: Working with Operators
- In this section we learn how to perform calculations with numbers and variables
- Simple arithmetic is performed with operators
- An operator is a symbol that acts upon an items or a variable
- You combine operators, items and variables into a part of a statement known as an expression
x + y - 3
- Shown below are the five binary arithmetic operators with examples of how they are used
- These operators are known as binary operators because they work with two items
Arithmetic Operators (Binary)
| Operator |
Description |
Example |
+ |
Adds or combines two items |
men = 10;
women = 15;
total = men + women;
|
- |
Subtracts one item from another |
income = 1000;
expenses = 750;
profit = income - expenses;
|
* |
Multiplies two items |
width = 20;
height = 30;
area = width * height;
|
/ |
Divides one item by another |
persons = 20;
cost = 30;
costPerPerson = cost / persons;
|
/ |
Calculates the remainder after dividing one item by another |
totalEggs = 65;
cartonSize = 12;
eggsLeft = totalEggs % cartonSize;
|
- JavaScript also has unary operators that work on only one item
- Shown below are three unary arithmetic operators with examples of how they are used
Arithmetic Operators (Unary)
| Operator |
Description |
Example |
Equivalent To |
- |
Changes the sign of (negates) an item's value |
-x |
x = 0 - x |
++ |
Increases the item's value by one |
x++ |
x = x + 1 |
-- |
Decreases the item's value by one |
x-- |
x = x - 1 |
Check Yourself
- Lets check our understanding of the increment operator with the following code
- Write down what you think the program will display before you check the answer
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Testing JavaScript Operators</title>
</head>
<body>
<script type="text/javascript">
var num = 1;
var x = ++num;
var y = x++;
var z = "The value equals " + 1;
var number = x + y;
document.write(num + "<br />");
document.write(x + "<br />");
document.write(y + "<br />");
document.write(z + "<br />");
document.write(number + "<br />");
</script>
</body>
</html>
|
Check answer
^ top
5.3.2: Assignment Operators
Assignment Operators
| Operator |
Description |
Example |
Equivalent To |
= |
Assigns the value of the expression on the right to the variable on the left |
x = 3 |
|
+= |
Adds the expression on the right to the variable on the left |
x += 3 |
x = x + 3 |
-= |
Subtracts the expression on the right from the variable on the left |
x -= 3 |
x = x - 3 |
*= |
Multiplies the expression on the right to the variable on the left and saves the result in the variable on the left |
x *= 3 |
x = x * 3 |
/= |
Divides the variable on the left by the expression on the right and saves the result in the variable on the left |
x /= 3 |
x = x / 3 |
%= |
Calculates the remainder from dividing variable on the left by the expression on the right and saves the result in the variable on the left |
x %= 3 |
x = x % 3 |
^ top
5.3.3: Calculating the Days Left in the Year
- Now let us use what we have learned to calculate the number of days left in a year
- We will create a function for this calculation
- As we create this function, we will show a general approach to writing functions
- If you are new to writing functions, you should follow this approach
Developing a Function
- In broad strokes, we need our function to:
- Create a
Date object for January 1 of next year
- Calculate the difference between the current Date and January 1 of next year
- We decide to name our function:
calcDays()
- The function will need a parameter for the current date
- The current date parameter will allow us to calculate the current year
- Then we can add one to the current year to get the next year
- With these thoughts in mind, we have a first design of our function:
function calcDays(currentDate) {
// 1. Create a date object for Jan. 1 of next year
// 2. Calculate the difference between currentDate
// and January 1
}
- Now let us refine each of the steps our function will take:
- Create a date object for January 1 of next year
- Extract the current year from the current date parameter
- Create a temporary date of January 1 of some year
- Add 1 to the current year to get the new year
- Set the temporary date to the new year
- Calculate the difference between
currentDate and January 1 of next year
- Convert both
currentDate and newYear to milliseconds
- Subtract
currentDate from newYear
- Convert the difference to days
- Return the number of days to the new year
- This set of instructions is known as an algorithm:
Algorithm: A sequence of precise instructions which leads to a solution
- The algorithm above is precise enough that we can easily convert it to JavaScript code
Function to Calculate the Number of Days to the New Year
1
2
3
4
5
6
7
8
9
10
11
|
function calcDays(currentDate) {
// 1. Create a date object for Jan. 1 of next year
nextYear = currentDate.getFullYear() + 1;
newYear = new Date("January 1, 2007");
newYear.setFullYear(nextYear);
// 2. Calculate the difference between currentDate
// and January 1
ms = newYear.getTime() - currentDate.getTime();
days = ms / (1000 * 60 * 60 * 24);
return days;
}
|
Designing Methods
^ top
5.3.4: Calling the calcDays() Function
- Now that we have the
calcDays() function, we need to use it in the web page for Dixon's New Year's Bash
- We update the
NYClock() function to make use of the calcDays() function
- This update is shown in the image below taken from the textbook on page JVS 68
- You can see the updated web site here
NYClock() Function Calling calcDays()

^ top
5.3.5: Summary
- In this section we looked at how to work with arithmetic in JavaScript
- JavaScript uses the following operators for arithmetic:
+ for addition
- for subtraction
* for multiplication
/ for division
% for modulus (remainder)
- The dash (minus sign) is also used for negation
- Since adding and subtracting 1 is so common, JavaScript has shortcut operators:
++ Increases the item's value by one
-- Decreases the item's value by one
- If you use a
++ or -- as part of a larger expression, you need to distinguish between pre and post operations
- When using
++ or -- before a variable, then the operation occurs before the variable is used before the variable is used
x = x + 1;
x = y;
- Otherwise, the operation occurs after the variable is used
x = y;
x = x + 1;
- In addition, we looked at assignment operators using the equal sign (=)
x = 3;
- Also, we looked at using additional operators to calculate values and assign them to the variable in one statement
- The general syntax is:
variable op= expression;
- Where
op is one of the five arithmetic operators: +, -, *, /, %
- Finally, we applied these concepts to calculating the number of days to the new year
Check Yourself
- What are the five operators JavaScript provides for arithmetic?
- What is meant by the term: expression?
- What are three different ways you can increase the value of a variable named
count by one?
^ top
Activity 5.3
Take one minute to read over the following Quick Quiz questions. We will discuss the questions in one minute.
Quick Quiz
^ top
5.4: Advanced Math, Conditions and Timing
Learner Outcomes
At the end of the lesson the student will be able to:
- Use the properties and methods of the
Math object
- Understand how JavaScript works with numeric values
- Work with conditional operators
- Run time-delayed and timed-interval commands
|
^ top
5.4.1: Working with Math Methods and Constants
- If you look at the current version of the web site, you notice that the number of days includes a fractional part
- The fractional part is the number of hours, minutes and seconds left in the day
- We want to convert this fractional part into hours, minutes and seconds
- To do this, we need to use some of the
Math object methods of JavaScript
Math Methods and Constants
Math Constants
^ top
5.4.2: Using the Math.floor() Method
NYClock() Function Using Math.floor()

Calculating the Hours, Minutes, and Seconds Left in the Year
- You can use the
Math.floor() method to calculate the hours, minutes, and seconds left in the year
- To calculate number of hours left in current day:
var hours = (days - Math.floor(days)) * 24;
- To calculate minutes left in current hour:
var minutes = (hours - Math.floor(hours)) * 60;
- To calculate seconds left in current minute:
var seconds = (minutes - Math.floor(minutes)) * 60;
- You can insert these statements into the
NYClock() function as shown on page JVS 73
^ top
5.4.3: Working with Numeric Values
- As you perform mathematical calculation, you run into situations where you need to work with the properties of numbers
- In this section we will look at how to examine the properties of numbers and how to specify how numbers are displayed
Handling Illegal Operations
- Some math operations can return values that are not numbers
- For instance, you ask the user to enter the cost and the number of people in a form
- You then divide the cost by the number of people to get the cost per person
- However, what happens if the user enters bad data such as letters for the number of people
var test = 5 / "two";
- When you performed the calculation, JavaScript would display the value "
NaN"
- You can use the
isNaN() function to test for this case
- Syntax:
isNaN(value)
- For example:
<script type="text/javascript">
var test = isNaN(5 / "two");
document.write(test + "<br />");
var test2 = isNaN(5 / 2);
document.write(test2);
</script>
- Produces the following output:
- Another illegal numerical operation is dividing by 0
var test = 5 / 0;
- You can use the
isFinite() function to test for this case
- Syntax:
isFinite(value)
- For example:
<script type="text/javascript">
var test = isFinite(5 / 0);
document.write(test + "<br />");
var test2 = isFinite(0 / 5);
document.write(test2);
</script>
- Produces the following output:
Specifying the Number Format
- When displaying a numeric value, JavaScript displays all the digits by default
- For example:
<script type="text/javascript">
var x = 1 / 4;
var y = 1 / 3;
document.write("x=" + x + "<br />");
document.write("y=" + y);
</script>
- Produces the following output:
- However, you can control number of digits displayed by browser using:
value.toFixed(digits)
- For example:
<script type="text/javascript">
var testValue = 3.45;
document.write(testValue.toFixed(0) + "<br />");
document.write(testValue.toFixed(1) + "<br />");
document.write(testValue.toFixed(2) + "<br />");
document.write(testValue.toFixed(3));
</script>
- Produces the following output:
Converting Between Numbers and Strings
- Sometimes you want to convert a number to a text string
- JavaScript will automatically convert it if you use a
+ operator to append a string
- For example:
testNum = 123;
testString = testNum + "";
- To go the other way, you can apply a numeric operator (other than
+) to a string
- For example:
testString = "123";
testNum = testString * 1;
- Another way to extract a number from a string is
parseInt()
- Syntax:
parseInt(text)
- For example:
<script type="text/javascript">
var height = parseInt("6 feet 1 inch");
var weight = parseInt("175.5 pounds");
var age = parseInt("age: 27");
document.write("height=" + height + "<br />");
document.write("weight=" + weight + "<br />");
document.write("age=" + age);
</script>
- Produces the following output:
- There are other useful numerical methods listed in the textbook on page JVS 76
^ top
5.4.4: Working with Conditional Operators
Test Conditions
- One way to create a Boolean expression is to use comparison operators
- For example:

- A condition always evaluates to either
true or false
- You can see the comparison operators below with examples of how they are used
Comparison Operators
| Math |
Name |
JavaScript |
Examples |
Result |
| = |
Equal to |
== |
5 == 10 2 == 2 |
false
true |
| ≠ |
Not equal to |
!= |
5 != 10 2 != 2 |
true
false |
| < |
Less than |
< |
5 < 10 5 < 5 5 < 2 |
true
false
false |
| ≤ |
Less than or equal to |
<= |
5 <= 10 5 <= 5 5 <= 2 |
true
true
false |
| > |
Greater than |
> |
5 > 10 5 > 5 5 > 2 |
false
false
true |
| ≥ |
Greater than or equal to |
>= |
5 >= 10 5 >= 5 5 >= 2 |
false
true
true |
Applying Conditions to the Time Format
- Let us apply our knowledge of conditional operators and comparisons to the formatting problem
- We will convert each formatting rule to a JavaScript statement
- This is shown in the following version of the
showTime() function
- Also, formatting to add leading zeros is included
- You can see the display with these enhancements in the Final New Year's Bash Web Site
Function showTime() with 12-Hour Formatting
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
function showTime(dateObj) {
var hours = dateObj.getHours();
var minutes = dateObj.getMinutes();
var seconds = dateObj.getSeconds();
// 1. If the hour < 12 then display the time as
// "A.M."; otherwise display it as "P.M."
var ampm = (hours < 12) ? " a.m." : " p.m.";
// 2. If hour > 12 then subtract 12 from hours
hours = (hours > 12) ? hours - 12 : hours;
// 3. If the hour is equal to 0, change it to 12
hours = (hours == 0) ? 12 : hours;
// add leading zeros to minutes and seconds < 10
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
return hours + ":" + minutes + ":" + seconds
+ ampm;
}
|
^ top
5.4.5: Running Timed Commands
- One item we still need to do for the Final New Year's Bash Web Site is to update the display every second
- To do this, we need to run the
NYClock() function at one-second intervals
- JavaScript has two methods for running timed commands:
- Time-delayed commands
- Timed-interval commands
Time-Delayed Commands
- Time-delayed command run after a particular amount of time has passed
- Syntax:
setTimeout("command", delay);
- For example, to run the
NYClock() function after 5 milliseconds have passed:
setTimeout("NYClock()", 5);
Timed-Interval Commands
- A Timed-interval command tells the browser to run same command repeatedly at specified intervals
- Syntax:
setInterval("command", interval);
- For example, to run the
NYClock() function repeatedly every second
setInterval("NYClock()", 1000);
- To stop a timed-interval command you use:
clearInterval();
Applying setInterval() to NYClock()
^ top
5.4.6: Summary
- In this section we looked at a variety of math operations and other topics
- We first looked at using the Math object to perform more advanced calculations
- To solve the problem with fractional digits, we used the Math.floor() method
- Then we discussed how to work with numeric values in JavaScript, such as formatting numbers
- Also, we looked at using comparison (or relational) operators to test numerical conditions
- We use this test condition with the conditional operator to improve the formatting of the count-down clock
- We finished with a discussion of running timed commands
Tips for Working with Operators and Expressions
- Never apply mathematical operations to text strings
- In case of a logical error involving a mathematical operation, use the
isFinite() and isNaN() functions to detect them
Check Yourself
- What conditional operator would you use to change the value of the
thisMonth variable to 12 if it equals 11, but otherwise leave it unchanged?
- What function would you use to test whether the value of the
thisMonth variable is a number or not?
- What command would you use to display the value of the thisDay variable with no decimal places?
- What statement would you use to run the function
calcMonth() after a 0.5 second delay?
- What statement would you use to run the
calcMonth() function every 0.5 seconds?
^ top
Activity 5.4
Take one minute to read over the following Quick Quiz questions. We will discuss the questions in one minute.
Quick Quiz
^ top
Wrap Up
Due Next: A5: Math and Dates (10/9/06)
Discussion 4 and Quiz 4 (10/9/06)
^ top
Home
| WebCT
| Announcements
| Schedule
| Room Policies
| Course Info
Help
| FAQ's
| HowTo's
| Links
Last Updated: November 18 2006 @17:39:46
|