JavaScript Mimi Opkins CECS 470
What We’ll Cover Today u What is JavaScript? u What can it do? u How to program your pages using JavaScript u What do JavaScript programs look like?
What is JavaScript? u Allows you to embed commands in an HTML page u JavaScript commands are loaded by the web browser as part of the page u Commands can also be triggered when the user clicks page items, form fields, etc.
What is JavaScript? (con’t.) u Interpreted Language u Powerful and simple u Limited sets of objects that cannot be extended like JAVA
Why Use a Scripting Language? u HTML is static u Can write small scripts that execute on the user’s browser instead of the server u Increased functionality
What Can JavaScript Do? u Provides a fairly complete set of built-in functions and commands Math Calculations Manipulate Strings Open new windows Verify form input
How to Program Your Page u JavaScript Commands are embedded in HTML documents between SCRIPT tags
What Does JavaScript Look Like? u Resembles many other languages like C++ or JAVA u Case-sensitive u Flexible - a single statement can cover multiple lines or multiple statements/line u Braces group statements into blocks
Hiding Your Scripts u To keep browsers that don’t support JavaScript from interpreting your script as HTML, hide it HTML comments <!-- Hide script from older browsers Alert(“This is JavaScript”); -->
Respecting “JavaScript- Challenged” Browsers u Since not all browsers support JavaScript, use the NOSCRIPT tags as an alternative
Comments u Single Line Comments use // // This is a single line comment u Multiple Line Comments start with /* and end with */ /* This comments extends across multiple lines */
Using Identifiers u Used to identify a variable, method or object u Must start with a letter or underscore and contain 0-9, a-z, A-Z
Built-In Datatypes u Integers u Floating-Point Numbers u Strings u Boolean
Object-Oriented Terms u An object is a collection of data and functions that have been grouped together u A function is a piece of code that performs a specific operation u An object’s functions are methods, its data is called properties
Major Components of the Browser u Window History Location Document Frame v Document Form –Form Elements Status Bar
Browser Object Hierarchy document frame1 document form1 form2 element 2element 3element 1 window
Using Built-In Objects u Individual JavaScript elements are objects u Access objects by specifying their name the active document object is document
Using Properties u To access a property, just use the object name followed by a ‘.’ and the property name address.length u To set a property house.color=“blue” u To create a property customer.name=“Joe Smith”
Using Methods u Works like properties for an object customer.Bill(5.12) u Or without one add(1,3)
Window Object u Top-level object that contains almost everything else in the JavaScript object system u Properties and methods can be used without referring to it explicitly
Window Properties u history - the list of visited URLs u location - the window’s URL, if any u frames - array containing the window’s frames, if any u document - the document contained within the window
Window Methods u alert() - pop up a warning message u confirm() - “OK” or “cancel” u prompt() - retrieve information u open() - open a new window u close() - close a window
Alert Example window.alert( "Welcome to\nJavaScript\n Programming!" ); Click Refresh (or Reload) to run this script again.
Alert Example
Prompt Example window.alert( "Welcome " + window.prompt("Enter your name"," ")); Click Refresh (or Reload) to run this script again.
Prompt Example
Document Object u Contained within each window or frame is a single document u Corresponds to the HTML itself
Document Properties u bgColor - page’s background color u fgColor - page’s foreground color u forms - array of forms u links - array of links u location - complete URL u lastModified - date document was last modified
Document Methods u open() - open the doc for writing u close() - close and format the doc u clear() - clear the contents u write() - write some text into doc u writeln() - write a line of text into doc
Printing a Line Example A First Program in JavaScript document.writeln( " Welcome to JavaScript Programming! " );
Printing a Line Example
Operators u Assignment (=) u Math (+ - * / % ) u Comparison (== != >=) u Logical (&& || !) u String (+)
Assignments u Item=“turtle dove”; u quantity=2; u day=‘Monday’; u for_sale=true; u price=29.97; u value=null;
Adding Numbers Example var firstNumber, // first string entered by user secondNumber, // second string entered by user number1, // first number to add number2, // second number to add sum; // sum of number1 and number2 // read in first number from user as a string firstNumber = window.prompt( "Enter first integer", "0" ); // read in second number from user as a string secondNumber = window.prompt( "Enter second integer", "0" ); // convert numbers from strings to integers number1 = parseInt( firstNumber ); number2 = parseInt( secondNumber ); // add the numbers sum = number1 + number2; // display the results document.writeln( " The sum is " + sum + " " );
Adding Numbers Example
Comparisons and Conditonal Statements u If/else clauses if (age<10) alert(“you are very young”); else alert(“you are very old”); if (name<“M”) alert(“your are in the first line”);
IF Example inname = window.prompt("Enter your name"," "); window.alert( "Welcome " + inname); if (inname == "Mimi") document.writeln("That is a great name"); Click Refresh (or Reload) to run this script again.
IF Example
Loops u While var a; while (a<10) { document.writeln(“item=“+a); a++; }
While Loop Example var total, // sum of grades gradeCounter, // number of grades entered gradeValue, // grade value average, // average of all grades grade; // grade typed by user // Initialization Phase total = 0; // clear total gradeCounter = 1; // prepare to loop
While Loop Example // Processing Phase while ( gradeCounter <= 10 ) { // loop 10 times // prompt for input and read grade from user grade = window.prompt( "Enter integer grade:", "0" ); // convert grade from a String to an integer gradeValue = parseInt( grade ); // add gradeValue to total total = total + gradeValue; // add 1 to gradeCounter gradeCounter = gradeCounter + 1; }
While Loop Example // Termination Phase average = total / 10; // calculate the average // display average of exam grades document.writeln( " Class average is " + average + " " );
While Loop Example
Loops (con’t.) u For for (var i=0;i<10; ++) { document.writlen(“Item=“ + i); } u Break immediately exits loop u Continue back to the top of the loop
For Loop Example Sum the Even Integers from 2 to 100 var sum = 0; for ( var number = 2; number <= 100; number += 2 ) sum += number; document.writeln ( " The sum of the even integers " + "from 2 to 100 is " + sum + " " );
For Loop Example
Variable Scope u If you make a direct variable assignment in a function, the variable becomes global u To define a local variable use the var statement var remainder;
Arrays u Predefined arrays history list, hyperlinks, frames u Uses [ ] for definition u The length property gives the size of the array
Array Example Sum the Elements of an Array var theArray = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]; var total1 = 0 for ( var i = 0; i < theArray.length; i++ ) total1 += theArray[ i ]; document.writeln( "Total using subscripts: " + total1 );
Array Example
Defining Functions u Use the function statement u Parameters are optional u A return statement is optional. If it is not used the function will return an undefined value
Function with No Parameters function warn() { alert(“I wouldn’t do that if I were you”); } u Invoked by: warn();
Function with Two Parameters and Return function add(a,b) { return(a+b); } u Invoked by: add(a,b);
Programmer-Defined Functions Example A Programmer-Defined square Function document.writeln( " Square the numbers from 1 to 10 " ); // square the numbers from 1 to 10 for ( var x = 1; x <= 10; ++x ) document.writeln( "The square of " + x + " is " + square( x ) + " " ); // The following square function's body is executed only // when the function is explicitly called. // square function definition function square( y ) { return y * y; }
Programmer-Defined Functions Example
User-Defined Objects u Actually just associative arrays u Can assign new data fields and methods freely u Create a function with the same name as the object type (constructor function) u Call the new operator to create new instances of the object
String Built-in Object u substring() - returns a portion of a string u charAt() - returns a single character in a string u indexOf() - returns the position of a character in a string
String Object Example Character Processing Methods var s = "ZEBRA"; var letters = "abcdefghijklmnopqrstuvwxyzabcdefghijklm"; document.writeln( " Character at index 0 in '" + s + "' is ” + s.charAt( 0 ) ); document.writeln( " The index of the characters jkl in '" + letters + "' is " + letters.indexOf('jkl') ); document.writeln( " The substring from positions 3,4,5 and 6 in '" + letters + "' is " + letters.substring(3,7) );
String Object Example
Date Built-in Object u new Date() - returns today’s date and time u new Date(year,month,day) - returns midnight on the given date u new Date(year,month,day,hours, minutes, seconds) - returns given date and time
Date Object Example var current = new Date(); document.writeln( "String representation: " + current.toString()); document.writeln( " getDate: " + current.getDate() + " getDay: " + current.getDay() + " getMonth: " + current.getMonth() + " getFullYear: " + current.getFullYear() + " getTime: " + current.getTime() + " getHours: " + current.getHours() + " getMinutes: " + current.getMinutes() + " getSeconds: " + current.getSeconds()); var anotherDate = new Date( 1999, 2, 18, 1, 5, 0, 0 ); document.writeln( " New Date: " + anotherDate );
Date Object Example
Math Built-In Object u Full suite of scientific and trignometric functions u Don’t create a Math object, just use the methods
Math Object Example document.writeln( "Square Root of 81: " + Math.sqrt(81)); document.writeln( " 5 raised to the 3rd power: " + Math.pow(5,3)); document.writeln( " 33.7 rounded: " + Math.round(33.7) );
Math Object Example
Form Elements u An array corresponding to the elements on a form u Each element has several properties of its own
Form Properties u name - name defined in tag u value - element’s value u checked - is the button checked? u selected - option selected? u text - text label of a list object u options - array of options in a list
Form Methods u submit() - causes browser to immediately submit the form u focus() - moves the text cursor into the field u blur() - moves the cursor out of a field u select() - selects the entire contents of a field
Form Validation Example
Handling Events u onLoad Document Loaded into Browser For documents and framesets u onUnload Document unloaded from Browser For documents and framesets u onSubmit Submit button pressed in a form For forms
Handling Events (con’t.) u onClick User has clicked on an element Radio buttons, pushbutton, checkboxes and links u onFocus Form field has become active Text Fields, password fields, etc.
Handling Events (con’t.) u onBlur Form field has become inactive Text Fields, password fields, etc. u onChange Form field has changed Text Fields, scrolling links and popup menus
Handling Events (con’t.) u onMouseOver Mouse is over the element Hypertext links u onSelect The selected area of a field has changed Text Fields
On Click Example Event Model - ONCLICK <INPUT TYPE = "button" VALUE = "Click Me!" ONCLICK = "alert( 'Hi there good lookin' )";>
On Click Example
OnMouseOver Example Event Model - ONMOUSEOVER <a href=" ONMOUSEOVER = "alert( 'The mouse over works' )";>
OnMouseOver Example
OnFocus OnBlur Example Name: Click here if you like this site
OnFocus OnBlur Example