JavaScript Events and Event Handlers • An event is an action that occurs within a Web browser or Web document. • An event handler is a statement that tells browsers what code to run in response to the specified event. • To insert an event handler as an HTML attribute, use the HTML code: <element onevent = “script”> • Example: JavaScript Events Two Important JavaScript Objects • The Date object contain information about a specified date and time. • The Math object is an object that can be used for performing mathematical tasks and storing mathematical values. Creating a Date Object • To store a date and time in a variable, use the JavaScript command variable = new Date("month day, year hours:minutes:seconds"); where variable is the name of the variable that contains the date object, and month, day, year, hours (24-hour clock), minutes, and seconds indicate the date and time to be stored in the object. • To create a date object containing the current date and time, use the constructor: variable = new Date(); Get and Set Date Methods • Date methods can be used to get information from a date object or to set a date object’s values The Set Date Methods Math Methods • Math methods are functions used for performing advanced calculations and mathematical operations such as: Constants in the Math Object • The Math object also stores numeric values for mathematical constants: Operators in JavaScript • An operator is a symbol used to act upon an item or a variable within a JavaScript expression. • The variables or expressions that operators act upon are called operands. • Types of operators: – Arithmetic – Assignment – Comparison - Logical - Conditional Binary Arithmetic Operators Some Other Arithmetic Operators • Increment operator: increases the value of the operand by 1. Example: x++; • Decrement operator: decreases the value of the operand by 1. Example: x--; • Negation operator: changes the sign of an item’s value Example: -x Assignment Operators Comparison Operators Logical Operators • Logical operators allow you to connect several expressions together. Conditional Operators • A conditional operator performs a comparison test and assigns one value if the condition is true and another value if the condition is false. Example: var ampm = (hour < 12) “AM” : “PM” ; A Complete Example: Putting It All Together Let’s create a web page that simulates rolling a pair of dice. 1. Display a button on the screen. 2. When the user presses the button (an event), use the Math object to generate a random number between 1 and 6. Do this twice. 3. Display the value of the dice roll in an alert popup on the web page. Save this file! We’ll be adding more to the web page next week.