© 2007 d. j. foreman (& u.h. st.clair) js-1 more javascript for beginners basic concepts

Click here to load reader

Upload: stephen-russell

Post on 17-Jan-2016

219 views

Category:

Documents


0 download

TRANSCRIPT

JavaScript

2007 D. J. Foreman (& U.H. St.Clair)JS-1More JavaScript for BeginnersBasic Concepts1Variables and Statements 2007 D. J. ForemanJS-22Basics2007 D. J. ForemanJS-3Variables: names that are place holders for dataX, x, myvalThe var prefix is needed for objects and arraysand to "privatize" a name inside a function

Expressions: perform computationsX*Cuberoot(B)

Statements: sentences that perform workX=x*y; // x and X are DIFFERENTdocument.write("aha
");3Variables: Naming Conventions2007 D. J. ForemanJS-4Each 'word' within the name of a variable usually gets capitalized:MySpecialNameA constant (name for something that NEVER changes) is usually all caps:Math.PI, Math.LOG10E,MYINTRATE4A strange variable statement2007 D. J. ForemanJS-5Normal syntax:I=I+1;

Shortened form:I++;

ONLY for adding 15Adding comments2007 D. J. ForemanJS-6Two kinds of JavaScript comments: // ignore remainder of this line /* ignore what's inside these markers */VSOne kind of HTML comment!-- ignore what's inside these markers --

Note: tag ends with 2 DASHES before the ">"

6One big problemSome browsers may not accept JavaScript,so we have to hide it from them...

2007 D. J. ForemanJS-7

7Hiding JavaScript (from old browsers)2007 D. J. ForemanJS-8

9Example 2: A Prompt Window2007 D. J. ForemanJS-10A PopUp Dialog

Display this line for every browser

10Events2007 D. J. ForemanJS-11Connection between JS and the system users actionsSome pre-defined events:OnLoad / OnUnloadOnClick / OnMouseOverOnFocus / OnBlur // see Prof. Hinton's websiteOnChange - lost focus and value changedOnSelect - text, textarea, password objectsOnSubmit - with the form objectMany events are connected to prompts by the browser11Object Hierarchy2007 D. J. ForemanJS-12BrowserWindowHistoryLocationDocumentLinksAnchorForms12About objects, their properties and methodsFormatting Documents with JS2007 D. J. ForemanJS-13Document Objects

some examples2007 D. J. ForemanJS-14document.title - contains the webpage titledocument.form (the form on the page)document.form.button1 (1st button on the form)14More Document Objects 2007 D. J. ForemanJS-15Datemydate_object=new Date();Mathx=Math.sqrt(xyz);framesframes[0] is the first framestringsxyz="my data"; I=xyz.length;"mydata" is a string, as is the variable xyz

15Some Document Properties 2007 D. J. ForemanJS-16alinkColorvlinkColorlinkColorbgColor fgColorlocationthe URL of this documenttitletext that appears in title-bar16Document Methods2007 D. J. ForemanJS-17objects have methods that perform workthese are some document-focused methodsclear()close()open()write()17Examples of work usage2007 D. J. ForemanJS-18Can 'get' and set properties of objectsdocument.title="this is my webpage title";X=document.title;

18Program building blocksFunctions2007 D. J. ForemanJS-19Functions - program building blocks2007 D. J. ForemanJS-20A function is a reusable code-block that will be executed by an event, or when the function is called.Functions accept input, process it, and deliver outputFunctions make Web pages dynamic!Function - user-defined sequence of codePlaced between Defined within 20Functions Format (Syntax)function function_name( ) {statements of the function go between the braces, and are ended with a semi-colon; }

Examplefunction myfunction(){alert("HELLO");}

2007 D. J. ForemanJS-21Examples of functions and codeFunctionHow to call a function.Function with arguments How to pass a variable to a function, and use the variable in the function.Function with arguments 2How to pass variables to a function, and use these variables in the function.Function that returns a valueHow to let the function return a value.A function with arguments, that returns a valueHow to let the function find the product of two arguments and return the result.The word function must be written in lowercase letters, otherwise a JavaScript error occurs!2007 D. J. ForemanJS-22Invoking (Calling) a Simple Function With a Button2007 D. J. ForemanJS-23Calling a Function

function myfunction(){alert("HELLO");}

onclick="myfunction()"

Function is being called23Functions with and without ArgumentsFunction arguments may be empty or non-emptyRemember: functions are always invoked in the bodyExamplesmyfunction(){The result (or work) of these statements is displayed, every time myfunction is called;}

myfunction(txt){The statements here display some text specified in the body, when myfunction is called;}

2007 D. J. ForemanJS-24SEE DEMO EXAMPLES24The function return statementThe return statement is used to specify the value that is returned from the function.

So, functions that are going to return a value must use the return statement.

2007 D. J. ForemanJS-25Return statement example + a variableThe function below should return the product of two numbers (a and b):var = product

function prod(a,b) { x=a*b; return x; }When you call the function above, you must pass along two parameters:product=prod(2,3);The returned value from the prod() function is 6, and it will be stored in the variable called product.2007 D. J. ForemanJS-26Objects within Forms2007 D. J. ForemanJS-27Text fields and areasPasswordCheckboxRadioSelectButtonResetSubmit27Limitations2007 D. J. ForemanJS-28Interpreter is hooked-into browserCant access files (open, read, write)28Control Statements 2007 D. J. ForemanJS-29Statements used to control the "flow" of execution within a JS program

if else conditional statementFor loop

Reason for Using Conditional StatementsVery often when you write code, you want to perform different actions for different decisions. You can use conditional statements In your code to do this.if...else statement - use this statement if you want to execute some code if the condition is true and another code if the condition is false*Example:

If you are taking 12 credit hours or more, pay full-time tuition; else, pay per-credit-hour fee2007 D. J. ForemanJS-30TRUEFALSEPay $5000Pay $600 * cr hr* This text was copied from the Web page at http://www.w3schools.com/js/js_if_else.asp30Syntax of if else statementif (condition) { code to be executed if condition is true }

else { code to be executed if condition is not true }2007 D. J. ForemanJS-31

The if else Statement2007 D. J. ForemanJS-32Basic Example

if (a==b) // note the TWO = signs{true part}else{false part}

ConditionWhat happens if Condition is trueWhat happens if Condition is false

32 if Statement Example2007 D. J. ForemanJS-33Better Example:if (these shoes==shoes on sale)(then){I will buy these shoes}

else{I will not buy these shoes}

ConditionWhat happens if Condition is trueWhat happens if Condition is false

33If (another example)2007 D. J. ForemanJS-34if (a > b)document.write("See? 'A' was bigger");elsedocument.write('See? "A" was smaller or equal');

NOTE: single quotes inside the double-quoted stringsor vice-versa34Real if Example2007 D. J. ForemanJS-35 //If the time is less than 10, //you will get a "Good morning, CS205 Friend!" greeting. //Otherwise you will get a "Good day, CS205 Attendee!" greeting.

var d = new Date(); var time = d.getHours();

if (time < 10) { document.write("Good morning, CS205 Friend!"); }

else { document.write("Good day, CS205 Attendee!"); } The for Statement2007 D. J. ForemanJS-36Very often when you write code, you want the same block of code to run over and over again in a row. Instead of adding several almost equal lines in a script we can use loops to perform a task like this.In JavaScript there are two different kind of loops:for - loops through a block of code a specified number of timeswhile - loops through a block of code while a specified condition is trueThe for loop is used when you know in advance how many times the script should run.*

* Text for this slide was copied from the Web page at http://www.w3schools.com/js/js_loop_for.asp36The for Statement2007 D. J. ForemanJS-37Must be lowercaseRepeats a set of instructions until a limit is reached (i.e. its a loop)Syntax: for (start ; test ; change)Example:for (i=1 ; i