890 likes | 903 Views
JavaScript. Mimi Opkins CECS 470. What We’ll Cover Today. What is JavaScript? What can it do? How to program your pages using JavaScript What do JavaScript programs look like?. What is JavaScript?. Allows you to embed commands in an HTML page
E N D
JavaScript Mimi Opkins CECS 470
What We’ll Cover Today • What is JavaScript? • What can it do? • How to program your pages using JavaScript • What do JavaScript programs look like?
What is JavaScript? • Allows you to embed commands in an HTML page • JavaScript commands are loaded by the web browser as part of the page • Commands can also be triggered when the user clicks page items, form fields, etc.
What is JavaScript?(con’t.) • Interpreted Language • Powerful and simple • Limited sets of objects that cannot be extended like JAVA
Why Use a Scripting Language? • HTML is static • Can write small scripts that execute on the user’s browser instead of the server • Increased functionality
What Can JavaScript Do? • 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 • JavaScript Commands are embedded in HTML documents between SCRIPT tags • <SCRIPT LANGUAGE=“JavaScript”> • </SCRIPT>
What Does JavaScript Look Like? • Resembles many other languages like C++ or JAVA • Case-sensitive • Flexible - a single statement can cover multiple lines or multiple statements/line • Braces group statements into blocks
Hiding Your Scripts • To keep browsers that don’t support JavaScript from interpreting your script as HTML, hide it HTML comments • <SCRIPT LANGUAGE=“JavaScript”> <!-- Hide script from older browsers Alert(“This is JavaScript”); -->
Respecting “JavaScript-Challenged” Browsers • Since not all browsers support JavaScript, use the NOSCRIPT tags as an alternative • <NOSCRIPT> • </NOSCRIPT>
Comments • Single Line Comments use // // This is a single line comment • Multiple Line Comments start with /* and end with */ /* This comments extends across multiple lines */
Using Identifiers • Used to identify a variable, method or object • Must start with a letter or underscore and contain 0-9, a-z, A-Z
Built-In Datatypes • Integers • Floating-Point Numbers • Strings • Boolean
Object-Oriented Terms • An object is a collection of data and functions that have been grouped together • A function is a piece of code that performs a specific operation • An object’s functions are methods, its data is called properties
Major Components of the Browser • Window • History • Location • Document • Frame • Document • Form • Form Elements • Status Bar
Browser Object Hierarchy window document frame1 document form2 form1 element 1 element 2 element 3
Using Built-In Objects • Individual JavaScript elements are objects • Access objects by specifying their name • the active document object is document
Using Properties • To access a property, just use the object name followed by a ‘.’ and the property name • address.length • To set a property • house.color=“blue” • To create a property • customer.name=“Joe Smith”
Using Methods • Works like properties for an object • customer.Bill(5.12) • Or without one • add(1,3)
Window Object • Top-level object that contains almost everything else in the JavaScript object system • Properties and methods can be used without referring to it explicitly
Window Properties • history - the list of visited URLs • location - the window’s URL, if any • frames - array containing the window’s frames, if any • document - the document contained within the window
Window Methods • alert() - pop up a warning message • confirm() - “OK” or “cancel” • prompt() - retrieve information • open() - open a new window • close() - close a window
Alert Example <HEAD> <SCRIPT LANGUAGE = "JavaScript"> window.alert( "Welcome to\nJavaScript\n Programming!" ); </SCRIPT> </HEAD> <BODY> <P>Click Refresh (or Reload) to run this script again.</P> </BODY> </HTML>
Prompt Example <HEAD> <SCRIPT LANGUAGE = "JavaScript"> window.alert( "Welcome " + window.prompt("Enter your name"," ")); </SCRIPT> </HEAD> <BODY> <P>Click Refresh (or Reload) to run this script again.</P> </BODY> </HTML>
Document Object • Contained within each window or frame is a single document • Corresponds to the HTML itself
Document Properties • bgColor - page’s background color • fgColor - page’s foreground color • forms - array of forms • links - array of links • location - complete URL • lastModified - date document was last modified
Document Methods • open() - open the doc for writing • close() - close and format the doc • clear() - clear the contents • write() - write some text into doc • writeln() - write a line of text into doc
Printing a Line Example <HTML> <HEAD> <TITLE>A First Program in JavaScript</TITLE> <SCRIPT LANGUAGE = "JavaScript"> document.writeln( "<H1>Welcome to JavaScript Programming!</H1>" ); </SCRIPT> </HEAD><BODY></BODY> </HTML>
Operators • Assignment (=) • Math (+ - * / % ++ - -) • Comparison (== != < <= > >=) • Logical (&& || !) • String (+)
Assignments • Item=“turtle dove”; • quantity=2; • day=‘Monday’; • for_sale=true; • price=29.97; • value=null;
Adding Numbers Example <SCRIPT LANGUAGE = "JavaScript"> 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( "<H1>The sum is " + sum + "</H1>" ); </SCRIPT>
Comparisons and Conditonal Statements • 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 <HEAD> <SCRIPT LANGUAGE = "JavaScript"> inname = window.prompt("Enter your name"," "); window.alert( "Welcome " + inname); </SCRIPT> </HEAD> <BODY> <SCRIPT LANGUAGE = "JavaScript"> if (inname == "Mimi") document.writeln("That is a great name"); </SCRIPT> <P>Click Refresh (or Reload) to run this script again.</P> </BODY> </HTML>
Loops • While var a; while (a<10) { document.writeln(“item=“+a); a++; }
While Loop Example <SCRIPT LANGUAGE = "JavaScript"> 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( "<H1>Class average is " + average + "</H1>" ); </SCRIPT>
Loops(con’t.) • For for (var i=0;i<10; ++) { document.writlen(“Item=“ + i); } • Break • immediately exits loop • Continue • back to the top of the loop
For Loop Example <HTML> <HEAD> <TITLE>Sum the Even Integers from 2 to 100</TITLE> <SCRIPT LANGUAGE = "JavaScript"> var sum = 0; for ( var number = 2; number <= 100; number += 2 ) sum += number; document.writeln ( "<BIG>The sum of the even integers " + "from 2 to 100 is " + sum + "</BIG>" ); </SCRIPT> </HEAD><BODY></BODY> </HTML>
Variable Scope • If you make a direct variable assignment in a function, the variable becomes global • To define a local variable use the var statement • var remainder;
Arrays • Predefined arrays • history list, hyperlinks, frames • Uses [ ] for definition • The length property gives the size of the array
Array Example <HTML> <HEAD> <TITLE>Sum the Elements of an Array</TITLE> <SCRIPT LANGUAGE = "JavaScript"> 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 ); </SCRIPT> </HEAD><BODY> </BODY> </HTML>