5. Using Operators, Expressions and Dates

What We Will Cover


Elucidations

Questions from last class?

Homework Questions?

Homework Discussion Questions

  1. What do you code to write the following text to a document?
    <img src='imgNumber.jpg' alt='' />
    
  2. How do we fix the errors in the file: debugger.html?

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

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:
    1. Calculate current date and time
    2. Calculate time remaining until New Year's Day
    3. 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

New Year's form layout

5.1.2: Inserting Values into a Form

  • In order to display the time and date values, we need to write values into the fields of the form
  • To set a value into the field of a form you use the JavaScript statement:
    document.formName.fieldName.value = fieldValue
    
  • For example, to write a date into the dateNow field of the clockForm:
    document.clockForm.dateNow.value = "9/25/2006";
    

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

NYClock function

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

  • To program a response to an event, we write an event handler
  • For a web page element, you can add event handlers directly to the element's tag as an attribute
  • The syntax to insert event handler as an attribute:
    <element onevent="script" ...> ...
    
  • For example, to respond to a click event:
    <input type="submit" name="clickme"
    value="Click Me!" onclick="alert('Thank You!')">
    
  • Produces the following form button and event action:

Running JavaScript When the Page is Loaded

  • One of the event handlers is onload
  • The load event occurs ("fires") when the browser completes loading of the web page
  • We can use this event to run our NYClock() function when the page loads
  • To do this, we add an onload event handler to the body element:
    <body onload="NYClock()">

5.1.4: Running JavaScript Commands as Links

  • You can run a JavaScript command as a link
  • This is like running the command in response to a click event
  • Syntax:
    <a href="javascript:script">content</a>
    
  • For example, the following code runs the calcTotal() function:
    <a href="javascript:calcTotal()">
      Calculate total cost
    </a>
    
  • This technique is often used for older browsers that do not support event handlers

5.1.5: Summary

  • In this section we learned how to create event handlers
  • Event handlers allow you to run functions in response to events occurring in a web page and web browser
  • The syntax to insert event handler as an attribute:
    <element onevent="script" ...> ...
    
  • Also in this section, we looked at how to set the values of fields in a web form:
    document.formName.fieldName.value = fieldValue
    

Check Yourself

  1. What is an event handler?
  2. What code would you write to insert the value "Friday" into a form named "weekdays" and a field named "today"?
  3. What attribute would you add to a button element to run the showImage() function when the button is clicked?
  4. What HTML code would you write to create a link that runs the showImage() function when the link is clicked?

Activity 5.1

Take one minute to read over the following Quick Quiz questions. We will discuss the questions in one minute.

Quick Quiz

  1. A function named showThis() executed its commands immediately after the page loaded. The event handler that was used to call the function was the event handler.
  2. A link is coded as <a href="javascript:calcNow()">Calculation</a.>. It could be rewritten as:
    1. <a href="calcNow()">Calculation</a>
    2. <a href="#" onclick="calcNow()">Calculation</a>
    3. <a href="onclick:calcNow()">Calculation</a>
    4. <a href="#">Calculation</a>
      (try it)

  3. An event handler is used to _______ functions and execute JavaScript commands.
    1. call
    2. delete
    3. create
    4. store

  4. Event handlers are the only way to control the execution of JavaScript commands.

    True
    False

    (reason)

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

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

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

  • To get the day of the month from a Date object, you use the syntax:
    dateObject.getDate()
  • Where dateObject is the name of the variable containing the Date object
  • For example:
    <script type="text/javascript">
      var dateNow = new Date();
      var monthDay = dateNow.getDate();
      document.write("Month day=" + monthDay);
    </script>
    
  • Produces the following output:

Retrieving the Month

  • To get the month from a Date object, you use the syntax:
    dateObject.getMonth()
  • Note that getMonth() returns 0 for January
  • Thus, we need to add 1 to value returned by getMonth()
  • For example:
    <script type="text/javascript">
      var dateNow = new Date();
      var month = dateNow.getMonth() + 1;
      document.write("Month=" + month);
    </script>
    
  • Produces the following output:

Retrieving the Year

  • To get the current year from a Date object, you use the syntax:
    dateObject.getFullYear()
  • For example:
    <script type="text/javascript">
      var dateNow = new Date();
      var year = dateNow.getFullYear();
      document.write("Year=" + year);
    </script>
    
  • Produces the following output:

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

  • To get the number of milliseconds since midnight of January 1, 1970 you use:
    dateObject.getTime()
  • For example:
    <script type="text/javascript">
      var dateNow = new Date();
      var ms = dateNow.getTime();
      document.write("Milliseconds=" + ms);
    </script>
    
  • Produces the following output:

5.2.3: Setting Date and Time Values

  • Besides retrieving values from a Date object, you can also set new values
  • For example, we could change the year of a Date object like this:
    <script type="text/javascript">
      var dateNow = new Date();
      document.write("Date this year=" + dateNow);
      var nextYear = dateNow.getFullYear() + 1;
      dateNow.setFullYear(nextYear);
      document.write("<br />Date next year=" + dateNow);
    </script>
    
  • Produces the following output:

  • For more set-methods of the Date object, see the textbook page JVS 60
  • Also, you can view a list by following the link below

More Information

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

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

NYClock function

5.2.6: Summary

  • In this section we looked at how to use the Date object
  • Specifically, we looked at how to create a specific date and time using the syntax:

    objName = new Date("month day, year hours:minutes:seconds");

  • Also, we looked at how to create a variable holding the current date and time
  • In addition, we looked at how to extract parts of the date and time information from a Date object
  • Then, we looked at how to change parts of the date and time
  • Both getting and setting value are done using get and set methods of a Date object
  • Finally, we used our new knowledge to create date and time formatting functions
  • Then we updated the NYClock() function to call these new functions

Check Yourself

  1. 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.?
  2. What command would you use to extract the month value from the examDate variable? What value would be returned by this method?
  3. What command would you use to extract the 4-digit year value from the examDate variable?
  4. 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)?
  5. What command would you use to create a variable named currentTime that stores the current date and time (whatever that may be)?

Activity 5.2

Take one minute to read over the following Quick Quiz questions. We will discuss the questions in one minute.

Quick Quiz

  1. When creating a Date object, the syntax is to set a variable equal to .
  2. If the Date object thisDate uses the getMonth() method, the result is:
    1. The name of the month
    2. The number and the name of the month
    3. The number of the month starting with January equal to 0
    4. The number of the month starting with January equal to 1

  3. If the date object thisDate uses the getTime() method, the result is:
    1. The hour of the day expressed in milliseconds
    2. The minute of a given hour expressed in milliseconds
    3. The time value, expressed in milliseconds, since January 1, 1970
    4. The time of day expressed in GMT format

  4. JavaScript will not allow a date/time format expressed as "February 24, 2007 14:35:05".

    True
    False

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

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
  • Unary operators can make your code more compact but can give unexpected results if you are not careful
  • For example, consider the code:
    <script type="text/javascript">
      var x = 5;
      var y = x++;
      document.write("x=" + x + " y=" + y);
    </script>
    
  • You may expect y to be 6 after this code executes
  • However, the code produces the following output:

  • The reason is that ++ after a variable (post-increment) is equivalent to:
    x = y;
    x = x + 1;
    
  • On the other hand, ++ before a variable (pre-increment) is equivalent to:
    x = x + 1;
    x = y;
    

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

5.3.2: Assignment Operators

  • You use operators when assigning values to variables as well
  • These types of operators are known as assignment operators
  • The most common assignment operator is the equal sign (=)
  • The syntax of an assignment operation is:
    variable = expression
  • Where expression is some combination of numbers, variables and operators
  • For example, the following assigns the value 25 to the variable sum:
    var sum = 25;
    sum = sum + 10;
    
  • Note that an assignment operation always replaces the value assigned to the variable on the left-hand side of the equals sign with the value calculated from the right-hand side

    New values overwrite old values

  • You can use additional operators to calculate values and assign them to the variable on the left all in one statement
    • Known as shortcut assignment operators
  • The general syntax is:
    variable op= expression;
  • Where op is one of the five arithmetic operators: +, -, *, /, %
  • For example, the following two statements create the same result:
    x = x + 3;
    x += 3;
    
  • Shown below are the assignment operators with examples of how they are used

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

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:
    1. Create a Date object for January 1 of next year
    2. 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:
    1. Create a date object for January 1 of next year
      1. Extract the current year from the current date parameter
      2. Create a temporary date of January 1 of some year
      3. Add 1 to the current year to get the new year
      4. Set the temporary date to the new year
    2. Calculate the difference between currentDate and January 1 of next year
      1. Convert both currentDate and newYear to milliseconds
      2. Subtract currentDate from newYear
      3. Convert the difference to days
      4. 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

  • Note the approach we took to designing our function
    1. First we decided what the function needed to do in broad terms
    2. Next we coded a header for the function and decided on a name
    3. function calcDays(currentDate) {
        // 1. Create a date object for Jan. 1 of next year
        // 2. Calculate the difference between currentDate
        //    and January 1
      }
      
    4. Also, based on what the function needed to do, we decided on its parameters
    5. Then we refined our design until it was easy to write the code
  • This approach is known as top-down design
  • Another name for it is stepwise refinement

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

NYClock function

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

  1. What are the five operators JavaScript provides for arithmetic?
  2. What is meant by the term: expression?
  3. What are three different ways you can increase the value of a variable named count by one?

Activity 5.3

Take one minute to read over the following Quick Quiz questions. We will discuss the questions in one minute.

Quick Quiz

  1. In the expression y = ++x, JavaScript adds 1 to the variable x and then passes the results to the variable y.

    True
    False

  2. Another way of writing t = t + x is:
    1. ++t
    2. t++
    3. t += x
    4. x = +t

  3. If x = 3 and if y = x--, then y = .

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

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

  • The Math object is used to perform mathematical tasks and store mathematical values
  • The Math object has several methods to perform advanced calculations
  • Syntax for applying a Math method:
    Math.method(expression)
  • Where method is one of the many methods of the Math object
  • For example:
    <script type="text/javascript">
      var x = 16;
      var y = Math.sqrt(x);
      document.write("Square root of " + x + " = " + y);
    </script>
    
  • Produces the following output:

  • You can see the Math methods on page JVS 69 of the textbook
  • Also, you can use the JavaScript Math Object Reference

Math Constants

  • Sometime you need a math constant like π and e
  • For example, the formula for the area of a circle is πr2
  • Writing this as Javascript:
    area = Math.PI * Math.pow(radius, 2);
    
  • You can see the Math constants on page JVS 70 of the textbook
  • Also, you can use the JavaScript Math Object Reference

5.4.2: Using the Math.floor() Method

  • For the countdown clock, we want to display the integer portion of the days left in the year
  • We can do this using the Math.floor() method
  • The Math.floor() method returns a value rounded down to the lowest integer
  • For example:
    <script type="text/javascript">
      var x = 123.456789;
      document.write("x=" + x + "<br />");
      document.write("floor(x)=" + Math.floor(x));
    </script>
    
  • Produces the following output:

  • The updated NYClock() function is shown in this image taken from the textbook on page JVS 70

NYClock() Function Using Math.floor()

NYClock function

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

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

5.4.4: Working with Conditional Operators

  • Recall that we had some remaining problems with the New Year's Bash Web Site
  • One problem is that the time is displayed in a 24-hour format but we need to display it in a 12-hour format
  • We can convert the time to a 12-hour format using these rules:
    1. If the hour < 12 then display the time as "a.m."; otherwise display it as "p.m."
    2. If the hour > 12 then subtract 12 from the value
    3. If the hour is equal to 0, change it to 12
  • The textbook shows a technique using the conditional operator
  • You can use the conditional operator to test whether a condition is true or flase
  • If the condition is true then one value is returned
  • If the condition is flase (not true) then a different value is returned
  • Syntax:
    variable = (condition) ? trueValue : falseValue;
    
  • Where the condition is a Boolean expression

Test Conditions

  • One way to create a Boolean expression is to use comparison operators
  • For example:

    Relational expression

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

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:
    1. Time-delayed commands
    2. 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()

  • You apply the setInterval() to NYClock() in the onload event handler for the body element
    <body onload="setInterval('NYClock()',1000)">
  • This gives you the one-second update for the Final New Year's Bash Web Site

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

  1. 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?
  2. What function would you use to test whether the value of the thisMonth variable is a number or not?
  3. What command would you use to display the value of the thisDay variable with no decimal places?
  4. What statement would you use to run the function calcMonth() after a 0.5 second delay?
  5. What statement would you use to run the calcMonth() function every 0.5 seconds?

Activity 5.4

Take one minute to read over the following Quick Quiz questions. We will discuss the questions in one minute.

Quick Quiz

  1. 1.To extract the first integer from a text string use the function:
    1. parseFloat()
    2. parseValue()
    3. parseNum()
    4. parseInt()

  2. When applying mathematical operations to text strings, JavaScript returns a numeric value of zero each time.

    True
    False

  3. Determine the correct formula to calculate the sales tax on a transaction where the variable px is the item's price and the variable tx_rt is the tax rate of 6.5%. The value of the calculation is assigned to a variable named sales_tx.
    1. tx_rt = sales_tx + px
    2. sales_tx = px / tx_rt
    3. tx_rt = px - sales_tx
    4. sales_tx = px * tx_rt

Wrap Up

Due Next:
A5: Math and Dates (10/9/06)
Discussion 4 and Quiz 4 (10/9/06)

Home | WebCT | Announcements | Schedule | Room Policies | Course Info
Help | FAQ's | HowTo's | Links

Last Updated: November 18 2006 @17:39:46