Presentation is loading. Please wait.

Presentation is loading. Please wait.

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.

Similar presentations


Presentation on theme: "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."— Presentation transcript:

1 JavaScript Mimi Opkins CECS 470

2 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?

3 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.

4 What is JavaScript? (con’t.) u Interpreted Language u Powerful and simple u Limited sets of objects that cannot be extended like JAVA

5 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

6 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

7 How to Program Your Page u JavaScript Commands are embedded in HTML documents between SCRIPT tags

8 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

9 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”); -->

10 Respecting “JavaScript- Challenged” Browsers u Since not all browsers support JavaScript, use the NOSCRIPT tags as an alternative

11 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 */

12 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

13 Built-In Datatypes u Integers u Floating-Point Numbers u Strings u Boolean

14 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

15 Major Components of the Browser u Window History Location Document Frame v Document Form –Form Elements Status Bar

16 Browser Object Hierarchy document frame1 document form1 form2 element 2element 3element 1 window

17 Using Built-In Objects u Individual JavaScript elements are objects u Access objects by specifying their name the active document object is document

18 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”

19 Using Methods u Works like properties for an object customer.Bill(5.12) u Or without one add(1,3)

20 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

21 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

22 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

23 Alert Example window.alert( "Welcome to\nJavaScript\n Programming!" ); Click Refresh (or Reload) to run this script again.

24 Alert Example

25 Prompt Example window.alert( "Welcome " + window.prompt("Enter your name"," ")); Click Refresh (or Reload) to run this script again.

26 Prompt Example

27 Document Object u Contained within each window or frame is a single document u Corresponds to the HTML itself

28 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

29 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

30 Printing a Line Example A First Program in JavaScript document.writeln( " Welcome to JavaScript Programming! " );

31 Printing a Line Example

32 Operators u Assignment (=) u Math (+ - * / % ++ - -) u Comparison (== != >=) u Logical (&& || !) u String (+)

33 Assignments u Item=“turtle dove”; u quantity=2; u day=‘Monday’; u for_sale=true; u price=29.97; u value=null;

34 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 + " " );

35 Adding Numbers Example

36 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”);

37 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.

38 IF Example

39 Loops u While var a; while (a<10) { document.writeln(“item=“+a); a++; }

40 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

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

42 While Loop Example // Termination Phase average = total / 10; // calculate the average // display average of exam grades document.writeln( " Class average is " + average + " " );

43 While Loop Example

44 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

45 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 + " " );

46 For Loop Example

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

48 Arrays u Predefined arrays history list, hyperlinks, frames u Uses [ ] for definition u The length property gives the size of the array

49 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 );

50 Array Example

51 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

52 Function with No Parameters function warn() { alert(“I wouldn’t do that if I were you”); } u Invoked by: warn();

53 Function with Two Parameters and Return function add(a,b) { return(a+b); } u Invoked by: add(a,b);

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

55 Programmer-Defined Functions Example

56 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

57 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

58 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) );

59 String Object Example

60 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

61 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 );

62 Date Object Example

63 Math Built-In Object u Full suite of scientific and trignometric functions u Don’t create a Math object, just use the methods

64 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) );

65 Math Object Example

66 Form Elements u An array corresponding to the elements on a form u Each element has several properties of its own

67 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

68 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

69 Form Validation Example

70

71

72

73

74

75

76

77

78 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

79 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.

80 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

81 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

82 On Click Example Event Model - ONCLICK <INPUT TYPE = "button" VALUE = "Click Me!" ONCLICK = "alert( 'Hi there good lookin' )";>

83 On Click Example

84 OnMouseOver Example Event Model - ONMOUSEOVER <a href="http://www.experian.com" ONMOUSEOVER = "alert( 'The mouse over works' )";> www.experian.com

85 OnMouseOver Example

86 OnFocus OnBlur Example Name: Email: Click here if you like this site

87 OnFocus OnBlur Example

88

89


Download ppt "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."

Similar presentations


Ads by Google