Chapter 1: JavaScript Primer · color: JavaScript JavaScript JavaScript src a }
XP Tutorial 2 New Perspectives on JavaScript, Comprehensive1 Working with Operators and Expressions...
-
Upload
paulina-beryl-caldwell -
Category
Documents
-
view
213 -
download
0
Transcript of XP Tutorial 2 New Perspectives on JavaScript, Comprehensive1 Working with Operators and Expressions...
Tutorial 2 New Perspectives on JavaScript, Comprehensive 1
XP
Tutorial 2
Working with Operators and Expressions
Creating a New Year’s Day Countdown Clock
Tutorial 2 New Perspectives on JavaScript, Comprehensive 2
XPObjectives
• Work with event handlers• Insert a value into a Web form field• Create and work with date objects• Extract information from date objects
Tutorial 2 New Perspectives on JavaScript, Comprehensive 3
XPObjectives
• Work with arithmetic, unary, conditional, and logical operators
• Understand the properties and methods of the Math object
• Understand how JavaScript works with numeric values
• Run time-delayed and timed-interval commands
Tutorial 2 New Perspectives on JavaScript, Comprehensive 4
XPWorking with onEvent Processing
• Hector’s vision for Web site– Clock that updates itself every second
• Function to be created will – Calculate current date and time – Calculate time remaining until New Year’s Day – Run once every second
Tutorial 2 New Perspectives on JavaScript, Comprehensive 5
XPForm Field Names
Tutorial 2 New Perspectives on JavaScript, Comprehensive 6
XPInserting the NYClock Function
Tutorial 2 New Perspectives on JavaScript, Comprehensive 7
XPUnderstanding Event Handlers
• Event – Action that occurs within a Web browser
• Event handler – Statement that tells browsers what code to run in
response to specified event
• Syntax to insert event handler as an attribute<element onevent="script" ...> ...
Tutorial 2 New Perspectives on JavaScript, Comprehensive 8
XPJavaScript Event Handlers
Tutorial 2 New Perspectives on JavaScript, Comprehensive 9
XPRunning JavaScript Commands as Links
• Syntax<a href="javascript:script">content</a>
• The following code runs the calcTotal() function
<a href="javascript:calcTotal()">
Calculate total cost
</a>
Tutorial 2 New Perspectives on JavaScript, Comprehensive 10
XPWorking with Dates
• Date object– Contains information about a specified date and
time– Syntax
variable = new Date("month day, year hours:minutes:seconds");
Tutorial 2 New Perspectives on JavaScript, Comprehensive 11
XPRetrieve the Date, Month, and Hour Values
• Date methods– Used to retrieve information from or modify a date
object
• Syntax to apply the getDate() methodDateObject.getDate()
Tutorial 2 New Perspectives on JavaScript, Comprehensive 12
XPRetrieve the Date, Month, and Hour Values
• Storing value of current year in a variable ThisDate = new Date("February 24, 2007
14:35:05");
thisYear = thisDate.getFullYear();
Tutorial 2 New Perspectives on JavaScript, Comprehensive 13
XPRetrieving the Hour, Minute, and Second Values
• Methods– DateObject.getSeconds()– DateObject.getMinutes(– DateObject.getHours()
Tutorial 2 New Perspectives on JavaScript, Comprehensive 14
XPExtracting Date and Time Values from Date Objects
Tutorial 2 New Perspectives on JavaScript, Comprehensive 15
XPSetting Date and Time Values for Date Objects
Tutorial 2 New Perspectives on JavaScript, Comprehensive 16
XPCreating a Date and Time Function
• showDate() function function showDate(dateObj) {
thisDate = dateObj.getDate();
thisMonth = dateObj.getMonth()+1;
thisYear = dateObj.getFullYear();
return thisMonth + "/" + thisDate + "/" + thisYear;
}
Tutorial 2 New Perspectives on JavaScript, Comprehensive 17
XPCreating a Date and Time Function
• showTime() functionfunction showTime(dateObj) {
thisSecond=dateObj.getSeconds();
thisMinute=dateObj.getMinutes();
thisHour=dateObj.getHours();
return thisHour + ":" + thisMinute + ":" +
thisSecond;
}
Tutorial 2 New Perspectives on JavaScript, Comprehensive 18
XPCalling the showDate() and showTime() Functions
Tutorial 2 New Perspectives on JavaScript, Comprehensive 19
XPWorking with Operators
• Operator symbol– Used to act upon an item or a variable within a
JavaScript expression
• Arithmetic operators – Perform simple mathematical calculations
Tutorial 2 New Perspectives on JavaScript, Comprehensive 20
XPArithmetic Operators
Tutorial 2 New Perspectives on JavaScript, Comprehensive 21
XPArithmetic Operators
• Binary operators– Work with two items in an expression
• Unary operators– Work on only one item
• Increment operator– Used to increase the value of an expression by 1
Tutorial 2 New Perspectives on JavaScript, Comprehensive 22
XPArithmetic Operators
• Decrement operator– Decreases an item’s value by 1
• Negation operator– Changes the sign of (or negates) an item’s value
Tutorial 2 New Perspectives on JavaScript, Comprehensive 23
XPUnary Operators
Tutorial 2 New Perspectives on JavaScript, Comprehensive 24
XPAssignment Operators
• Used when assigning values to items within a JavaScript statement
• The following expressions create the same result
x = x + y;
x += y;
Tutorial 2 New Perspectives on JavaScript, Comprehensive 25
XPAssignment Operators
Tutorial 2 New Perspectives on JavaScript, Comprehensive 26
XPCalculating the Days Left in the Year
• Function needs to function calcDays(currentDate) {
create a date object for January 1 of next year
calculate the difference between currentDate and
January 1
}
Tutorial 2 New Perspectives on JavaScript, Comprehensive 27
XP Adding Commands to the calcDays() Function
Tutorial 2 New Perspectives on JavaScript, Comprehensive 28
XPCalling the calcDays() Function
Tutorial 2 New Perspectives on JavaScript, Comprehensive 29
XP Working with Math Methods and Constants
• Math object – Used to perform mathematical tasks and store
mathematical values
• Math methods– Used to perform advanced calculations
• Syntax for applying a Math methodMath.method(expression)
Tutorial 2 New Perspectives on JavaScript, Comprehensive 30
XPMath Methods
Tutorial 2 New Perspectives on JavaScript, Comprehensive 31
XPMath Constants
Tutorial 2 New Perspectives on JavaScript, Comprehensive 32
XPUsing the Math.floor() Method
Tutorial 2 New Perspectives on JavaScript, Comprehensive 33
XPCalculating 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 hourvar minutes = (hours - Math.floor(hours))*60;
• To calculate seconds left in current minutevar seconds = (minutes - Math.floor(minutes))*60;
Tutorial 2 New Perspectives on JavaScript, Comprehensive 34
XPControlling How JavaScript Works with Numeric Values
• NaN– Not a Number
• isNaN()– Used to check whether a value is numeric– Syntax: isNaN(value)
Tutorial 2 New Perspectives on JavaScript, Comprehensive 35
XPSpecifying the Number Format
• To control number of digits displayed by browser
value.toFixed(n)
• Applying the toFixed() functiontestValue = 2.835;
testValue.toFixed(0) // returns "3"
testValue.toFixed(1) // returns "2.8"
testValue.toFixed(2) // returns "2.84"
Tutorial 2 New Perspectives on JavaScript, Comprehensive 36
XP Numeric Functions and Methods
Tutorial 2 New Perspectives on JavaScript, Comprehensive 37
XPWorking with Conditional Operators
• Conditional operator – Tests whether a certain condition is true or not– Syntax
(condition) ? trueValue : falseValue
• Comparison operator – Compares value of one expression to another
Tutorial 2 New Perspectives on JavaScript, Comprehensive 38
XPComparison Operators
Tutorial 2 New Perspectives on JavaScript, Comprehensive 39
XPLogical Operators
Tutorial 2 New Perspectives on JavaScript, Comprehensive 40
XPRunning Timed Commands
• Time-delayed command – Run after a particular amount of time has passed– Syntax
setTimeout("command", delay);
Tutorial 2 New Perspectives on JavaScript, Comprehensive 41
XPRunning Commands at Specified Intervals
• Timed-interval command– Instructs browser to run same command
repeatedly at specified intervals– Syntax
setInterval("command",interval);
– Method to stop commandclearInterval();
Tutorial 2 New Perspectives on JavaScript, Comprehensive 42
XPPerforming Special Mathematical Tasks
• Math.floor(), Math.ceil(), and Math.round() methods – Used to round values to the next highest, next
lowest, and nearest integer
• No Math methods for– Rounding values to decimals
Tutorial 2 New Perspectives on JavaScript, Comprehensive 43
XPGenerating Random Numbers
• Math.random() method– Generates random values
• Generating random number between 0 and 10
var randValue = 10*Math.random();
• Generating random number from 20 to 30var randValue = 20 + 10*Math.random();
Tutorial 2 New Perspectives on JavaScript, Comprehensive 44
XPTips for Working with Operators and Expressions
• Use unary and assignment operators to create compact code
• When performing advanced mathematical calculations– Use constants from the Math object
• Never apply mathematical operations to text strings
Tutorial 2 New Perspectives on JavaScript, Comprehensive 45
XPTips for Working with Operators and Expressions
• In case of logical error involving a mathematical operation– Use the isFinite() and isNaN() functions
• Use the toFixed() method to– Format numeric output