Javascript Programming Variables, Functions, Objects, and Events

Brad Rippe [email protected]

Agenda

„ Questions „ FYI - New Edition of the book in the bookstore „ Lecture 2 – Variables, Functions and Objects „ Assignment 2 „ Quiz 1 „ Hand in Assignment 1

Javascript

„ „ Interpreted code „ Basic instructions are called “statements”

„ alert(‘This is a statement); „ var studentNum = 30; // statement too

„ Sequential order of execution „ Predefined functionality executed by engine in the browser

1 Reserved Words

abstract else instanceof switch boolean enum int synchronized break export interface this byte extends long throw case false native throws catch final new transient char finally null true class float package try const for private typeof continue function protected var debugger public void default if return volatile delete implements short while do import static with double in super

Variables

„ Must be declared with the “var” reserved word „ var name = “Brad”; „ var total = 35.00; „ var isResourceAvailable = false; „ var assignNum = 1, assignDes = “description”;

„ Variable names must start with a alpha character, “_” or “$” „ Variable names should be descriptive „ $savingsAccount „ savingsAccount

Variable Naming Conventions

„ Start with a lower case letter for the first word „ An consecutive words are capitalized

„ var name = “Brad”; // single word vars

„ var firstName = “Brad”;

„ var lastName = “Rippe”;

2 Try Using Variables

Example 1

Variables…

Example 2 - Try

Functions

„ Functions are away of organizing statements into one callable statement „ Declared before called „ Usually accomplish one task, i.e.,

printName(); validateForm(); checkBrowser(); swapImages();

3 Defining Functions function nameOfFunction(parameters) { statements; }

„ function is a javascript reserved word. It tells the javascript engine you are defining a function. „ nameOfFunction is an arbitrary name, an identifier which can be referred to later or elsewhere in the html file. „ Parameters are a list of variables that are available to the function. „ {} denote the beginning and ending of the function definition. „ Assume the rest of the slides are from within tags.

Example Function without Parameters list

function printName() { document.write(“”); document.writeln(“Joe”); document.write(“”); document.write(“”); document.writeln(“Steve”); document.write(“”); document.write(“”); document.writeln(“Mary”); document.write(“”); }

printName();

Example 3

Problems: Example Function without Parameters List

„ Repetitive code „ Hard to follow „ More work than needed „ can be accomplished with parameter passing

4 Parameter Passing

Example Function passing parameters function printName(name) { document.write(“”); document.writeln(name); document.write(“”); } printName(“Joe”); printName(“Steve”); printName(“Mary”);

Example 4 - Try

Parameter Passing printName(“Joe”); printName(“Steve”); printName(“Mary”);

„ Note the code above passes values “Joe”, “Steve”, and “Mary” „ The value of the variable name is changed with each call.

5 Variable

„ Variables only exist in the block of code that they are defined. „ References to variables outside they’re visible scope causes an error.

Variables out of scope function printName(name) { document.write(“”); document.writeln(name); document.write(“”); } printName(“Joe”); printName(“Steve”); printName(“Mary”); printName(name);

Global Variables var someOtherName = “My Name”; Global Scope function printName(name) { Local Scope document.write(“”); document.writeln(name); document.write(“”); } printName(“Joe”); printName(“Steve”); printName(“Mary”); printName(someOtherName);

6 Functions that return value

„ utility functions: „ calculateTax() „ validateEmail() „ computeMedian() „ average_numbers(a, b, ) – Note??

„ Statement that invoked the method (function) will receive a value.

Functions that return value function printName(name) { document.write(“”); document.writeln(name); document.write(“”); return “printed”; }

Example 5 - Try

Functions that return value

var name = printName("Joe"); document.writeln("
"); document.writeln(name);

name = printName("Steve"); document.writeln("
") document.writeln(name);

name = printName("Mary”); document.writeln("
") document.writeln(name);

Example 5

7 Returning Integer Value function average_numbers(a, b, c) { var sum_of_numbers = a + b + c; var result = sum_of_numbers / 3;

return result; }

Example 6, 7, 8

Problems

„ average_numbers(a, b, c)

„ Use the convention „ Function names should start with a lower-case letter and any consecutive words should be capitalized. „ Parameters should be descriptive „ a : num1 „ b : num2 „ C : num3

Javascript Objects

„ Used to store like data „ Usually model real world entities „ Person „ Book „ Product „ CD „ Similar to a function definition/declaration „ Need to use the keyword new when instantiating Objects

8 How do we define an Object?

„ function Book(title, author, callNumber) { this.title = title; this.author = author; this.callNumber = callNumber; } …

Book javascript = new Book(“Javascript”, “Don Gosselin”, “js2345”);

document.writeln(javascript.title);

Example 9

Javascript Objects

„ Array – creates new array objects „ Boolean – creates new Boolean objects „ Date Retrieves and manipulates dates and times „ Error Returns run-time error information „ Function – creates new function objects „ Global – represents the javascript built-in method „ Math – contains methods and properties for performing mathematical calculations „ Number – contains methods and properties for manipulating numbers „ Object – provides common functionality to all built-in Javascript objects „ RegExp – contains properties for finding and replacing in text strings „ String – contains methods and properties for manipulating text strings

Object functions function Book(title, author, callNumber) { this.title = title; this.author = author; this.callNumber = callNumber;

// we use printBook, although we could call it anything // to reference the printBook function this.printBook = printBook; // the “()” is left off because “printBook()” denotes a function call } function printBook() { document.writeln("Title: "); document.writeln(this.title); document.writeln("
Author: "); document.writeln(this.author); document.writeln("
Call Number: "); document.writeln(this.callNumber); }

Example 10

9 Calling Object methods

// Notice construction of the object is the same // Now to print the object, we simply // call the printBook(); var book = new Book("Javascript", "Don Gosselin", "js2345");

// use dot notation to call object methods (functions) book.printBook();

Object Key Points

„ Attributes (variables) characteristics

„ Methods (functions) behavior

„ JavaScript supports several types of objects. They are as follows: „ User-defined objects defined by the programmer „ Core or built-in objects, such as Date, String, and Number „ Browser and Document objects

Skip Object Inheritance

„ Page 62 & 63

10 Events

„ An event is a specific circumstance that is monitored by Javascript. Examples „ Mouse clicks „ Mouse over „ Loads „ Blur „ Focus „ Mouse out „ Select „ Unload

„ Allows us to interact with the users „ Manipulate the document or react to the user’s actions

HTML Forms

„ Allow users to send data to a process.

The body of the form goes here, including input devices for filling out the form

HTML Form Elements

Button Select Text File Textarea Hidden Password Submit Checkbox Image Radio Reset

11 Example Event Handling

Example Event Handling

Example Error

„ Remember HTML is NOT case sensitive, so onClick, onCLICK, OnClick are the same.

12 Getting User Data

„ Prompt the user for input „ prompt(message); var someInput = prompt(‘Type anything’); alert(‘You typed ‘+someInput);

Example 12

Overriding the browser’s event handling

… … Fullerton College

Example 13

MouseOver and Out

Fullerton College

13 Assignment 2

Questions???

14