Download presentation
Presentation is loading. Please wait.
Published byStephen Russell Modified over 9 years ago
2
© 2007 D. J. Foreman (& U.H. St.Clair) JS-1 More JavaScript for Beginners Basic Concepts
3
Variables and Statements ©2007 D. J. Foreman JS-2
4
Basics ©2007 D. J. Foreman JS-3 Variables: names that are place holders for data X, x, myval The var prefix is needed for objects and arrays and to "privatize" a name inside a function Expressions: perform computations X*Cuberoot(B) Statements: sentences that perform work X=x*y; // x and X are DIFFERENT document.write("aha ");
5
Variables: Naming Conventions ©2007 D. J. Foreman JS-4 Each 'word' within the name of a variable usually gets capitalized: MySpecialName A constant (name for something that NEVER changes) is usually all caps: Math.PI, Math.LOG10E, MYINTRATE
6
A strange variable statement ©2007 D. J. Foreman JS-5 Normal syntax: I=I+1; Shortened form: I++; ONLY for adding 1
7
Adding comments ©2007 D. J. Foreman JS-6 Two kinds of JavaScript comments: // ignore remainder of this line /* ignore what's inside these markers */ VS One kind of HTML comment !-- ignore what's inside these markers -- Note: tag ends with 2 DASHES before the ">"
8
One big problem Some browsers may not accept JavaScript, so we have to hide it from them... © 2007 D. J. Foreman JS-7
9
Hiding JavaScript (from old browsers) ©2007 D. J. Foreman JS-8 <!-- hiding JavaScript These lines might confuse the browser, so the comment tags hide them. The and tags will be ignored (remember the rule about unknown tags?) //--
10
Example 1: writing to the page ©2007 D. J. Foreman JS-9 <!-- hide the Javascript document.write (“I think we’re in trouble,Captain!"); // end of hide -->
11
Example 2: A Prompt Window ©2007 D. J. Foreman JS-10 A PopUp Dialog <!-- hide from non-js browsers engrname = window.prompt("What's the engineer's name?",""); // pop-up text document.write("Thanks! Beam me up, " + engrname + "!! "); // note use of the "+" sign --> Display this line for every browser
12
Events ©2007 D. J. Foreman JS-11 Connection between JS and the system users’ actions Some pre-defined events: OnLoad / OnUnload OnClick / OnMouseOver OnFocus / OnBlur // see Prof. Hinton's website OnChange - lost focus and value changed OnSelect - text, textarea, password objects OnSubmit - with the form object prompts Many events are connected to prompts by the browser
13
Object Hierarchy ©2007 D. J. Foreman JS-12 Browser WindowHistoryLocation Document Links AnchorForms
14
About objects, their properties and methods Formatting Documents with JS ©2007 D. J. Foreman JS-13
15
Document Objects some examples ©2007 D. J. Foreman JS-14 document.title - contains the webpage title document.form (the form on the page) document.form.button1 (1st button on the form)
16
More Document Objects ©2007 D. J. Foreman JS-15 Datemydate_object=new Date(); Mathx=Math.sqrt(xyz); framesframes[0] is the first frame stringsxyz="my data"; I=xyz.length; "mydata" is a string, as is the variable xyz
17
Some Document Properties ©2007 D. J. Foreman JS-16 alinkColor vlinkColor linkColor bgColor fgColor locationthe URL of this document titletext that appears in title-bar
18
Document Methods ©2007 D. J. Foreman JS-17 objects have methods that perform work these are some document-focused methods clear() close() open() write()
19
Examples of work usage ©2007 D. J. Foreman JS-18 Can 'get' and ‘set’ properties of objects document.title="this is my webpage title"; X=document.title;
20
Program building blocks Functions ©2007 D. J. Foreman JS-19
21
Functions - program building blocks ©2007 D. J. Foreman JS-20 A 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 output Functions accept input, process it, and deliver output Functions make Web pages dynamic! Functions make Web pages dynamic! Function - user-defined sequence of code Placed between Defined within
22
Functions – Format (Syntax) function function_name( ) {statements of the function go between the braces, and are ended with a semi-colon; } Example function myfunction() { alert("HELLO"); } ©2007 D. J. Foreman JS-21
23
Examples of functions – and code Function How to call a function. Function Function with arguments How to pass a variable to a function, and use the variable in the function. Function with arguments Function with arguments 2 How to pass variables to a function, and use these variables in the function. Function with arguments 2 Function that returns a value How to let the function return a value. Function that returns a value A function with arguments, that returns a value How to let the function find the product of two arguments and return the result. A function with arguments, that returns a value function The word function must be written in lowercase letters, otherwise a JavaScript error occurs! ©2007 D. J. Foreman JS-22
24
Invoking (Calling) a Simple Function – With a Button ©2007 D. J. Foreman JS-23 Calling a Function function myfunction() { alert("HELLO"); } <input type="button" value="Call function"> onclick="myfunction()" Function is being “called”
25
Functions with and without Arguments Function arguments may be empty or non-empty Remember: functions are always invoked in the body Examples 1.myfunction() {The result (or “work”) of these statements is displayed, every time myfunction is called; } 2.myfunction(txt) {The statements here display some text specified in the body, when myfunction is called; } ©2007 D. J. Foreman JS-24 SEE DEMO EXAMPLES
26
return The function return statement The 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. Foreman JS-25
27
Return statement example + a variable The 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); product The returned value from the prod() function is 6, and it will be stored in the variable called product. ©2007 D. J. Foreman JS-26
28
Objects within Forms ©2007 D. J. Foreman JS-27 Text fields and areas Password Checkbox Radio Select Button Reset Submit
29
Limitations ©2007 D. J. Foreman JS-28 Interpreter is ‘hooked-into’ browser Can’t access files (open, read, write)
30
Control Statements © 2007 D. J. Foreman JS-29 Statements used to control the "flow" of execution within a JS program oif … else conditional statement oFor … loop
31
Reason for Using Conditional Statements Very 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 fee ©2007 D. J. Foreman JS-30 TRUEFALSE Pay $5000Pay $600 * cr hr
32
Syntax of if … else statement if (condition) { code to be executed if condition is true } else { code to be executed if condition is not true } ©2007 D. J. Foreman JS-31
33
The if … else Statement ©2007 D. J. Foreman JS-32 Basic Example if (a==b) // note the TWO = signs {true part } else {false part } Condition What happens if Condition is true What happens if Condition is false
34
if Statement Example ©2007 D. J. Foreman JS-33 Better Example: if (these shoes==shoes on sale) (then) {I will buy these shoes } else {I will not buy these shoes } Condition What happens if Condition is true What happens if Condition is false
35
If (another example) ©2007 D. J. Foreman JS-34 if (a > b) document.write("See? 'A' was bigger"); else document.write('See? "A" was smaller or equal'); NOTE: single quotes inside the double-quoted strings or vice-versa
36
Real if … Example ©2007 D. J. Foreman JS-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!"); }
37
The for … Statement ©2007 D. J. Foreman JS-36 Very 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 times while - loops through a block of code while a specified condition is true The for loop is used when you know in advance how many times the script should run.*
38
The for Statement ©2007 D. J. Foreman JS-37 Must be lowercase Repeats a set of instructions until a limit is reached (i.e. it’s a loop) Syntax: for (start ; test ; change) Example: for (i=1 ; i<10; i++) {instructions to be repeated go here} In English: “Starting with ‘1’, if a number is smaller than 10, add ‘1’ to that number until you reach 10!”
39
for Statement Components ©2007 D. J. Foreman JS-38 for (i=1 ; i<10; i++) {instructions to be repeated go here} In English: “Starting with ‘1’, if a number is smaller than 10, add ‘1’ to that number!” Control variable name Initial value of control variable Loop continuation condition Increment of control variable
40
For … Example – explanation ©2007 D. J. Foreman JS-39 This example defines a loop that starts with i=0. The loop will continue to run as long as i is less than, or equal to 10. i will increase by 1 each time the loop runs. Note: The increment parameter could also be negative, and the <= could be any comparing statement.* generic name
41
For … Example – code ©2007 D. J. Foreman JS-40 FOR loop example var i=0; for (i=0;i<=10;i++) { document.write("The number is " + i); document.write(" "); }
42
For … Example - result ©2007 D. J. Foreman JS-41 The number is 0 The number is 1 The number is 2 The number is 3 The number is 4 The number is 5 The number is 6 The number is 7 The number is 8 The number is 9 The number is 10 Cool!
43
© 2007 D. J. ForemanJS-m42 String, Math, Date, Array, & Miscellaneous Methods & Properties
44
© 2007 D. J. Foreman JS-m43 String Object Methods & Properties anchor( ) big( ) blink( ) bold( ) charAt( ) fontcolor( ) fontsize( ) indexOf( ) italics( ) lastIndexOf( ) link( ) small( ) sub( ) sup( ) substr(start, length) substring(start, end) toLowerCase( ) toUpperCase( ) A “string” is a sequence of characters The String object is used to manipulate a stored piece of text.
45
Window.open Syntax ©2007 D. J. Foreman JS-44 Parameters URL, if any Name for new window Size attributes NOTEs: Quotes around WHOLE attribute string But no quotes around values in attributes
46
© 2007 D. J. Foreman JS-m45 String function:indexOf Purpose: Purpose: Find a string’s location in another string (the “string” to be found may be a single character) Method: Method: How to use the indexOf() method to return the position of the first occurrence of a specified string value in a string. Look for more information here!here
47
© 2007 D. J. Foreman JS-m46 Example: indexOf Let x be a string variable (maybe from some kind of input operation) that currently has the value: "DJ Foreman" We want to see if it contains an "F“ and where the “F” is located in the string: x = DJ Foreman n = x.indexOf("F"); n now has the index position of the "F" Remember that we start counting at ZERO So J now has the value of 3 Why is it 3 and not 2? DJ Foreman 0
48
Code Example: indexOf ©2007 D. J. Foreman JS-47 IndexOf Example var str="DJ Foreman!"; document.write(str.indexOf("F") + " "); document.write(str.indexOf("e") + " "); document.write(str.indexOf("n"));
49
© 2007 D. J. Foreman JS-m48 Example: lastindexOf, length X="DJ Foreman, Ph. D."; document.write(X.lastIndexOf(" ")+" "); document.write(X.length); Result is:15 17
50
String Examples with code Return the length of a string How to use the length property to find the length of a string. Return the length of a string Style strings How to style strings. Style strings The indexOf() method How to use the indexOf() method to return the position of the first occurrence of a specified string value in a string. The indexOf() method The match() method How to use the match() method to search for a specified string value within a string and return the string value if found The match() method Replace characters in a string - replace() How to use the replace() method to replace some characters with some other characters in a string. Replace characters in a string - replace() ©2007 D. J. Foreman JS-49
51
© 2007 D. J. Foreman JS-m50 Example of substring [substr] Purpose: copy a piece of a string, given its start and ending position Let X be a string variable (maybe from some kind of input operation) that currently has the value: "DJ Foreman, Ph. D." If we want the "Foreman": M=X.indexOf(" ")+1;// finds the 1 st char after the blank N=X.indexOf(",");// finds the comma Y=X.substring(M,N);// gets the "Foreman" into Y
52
What’s an array? The array object is used to store multiple values in a single variable. An ordered arrangement of data elements A vector is a one dimensional array A matrix is a two-dimensional array An array can be as simple as a pricing table held in memory for instant access by an order entry program For more information, look here!here Array object ©2007 D. J. Foreman JS-51
53
Simple Array – Visual Example ©2007 D. J. Foreman JS-52 Var MyHeight SylviaWinnieChasidaLili 5’2”5’5”5’4”5’7” new Array 1234
54
Array object and code Create an array Create an array, assign values to it, and write the values to the output. Create an array For...In Statement How to use a for...in statement to loop through the elements of an array. For...In Statement Join two arrays - concat() How to use the concat() method to join two arrays. Join two arrays - concat() Put array elements into a string - join() How to use the join() method to put all the elements of an array into a string. Put array elements into a string - join() Literal array - sort() How to use the sort() method to sort a literal array. Literal array - sort() Numeric array - sort() How to use the sort() method to sort a numeric array. Numeric array - sort() ©2007 D. J. Foreman JS-53
55
Array Example ©2007 D. J. Foreman JS-54 var mycars = new Array(); mycars[0] = "1989 Merkur Scorpio"; mycars[1] = "1996 Nissan Maxima"; mycars[2] = "2001 Toyota Sienna"; mycars[3] = "1998 BMW 528i"; mycars[4] = "1997 Mercedes Benz E320 -- for sale!"; mycars[5] = "2003 Toyota Avalon"; for (i=0;i<mycars.length;i++) { document.write(mycars[i] + " "); }
56
Array Example Result ©2007 D. J. Foreman JS-55 1989 Merkur Scorpio 1996 Nissan Maxima 2001 Toyota Sienna 1998 BMW 528i 1997 Mercedes Benz E320 -- for sale! 2003 Toyota Avalon
57
© 2007 D. J. Foreman JS-m56 Some Math Object Methods abs( ) ceil( ), floor( ) exp( ) log( ) max( ), min( ) pow( ) random( ) round( ) sqrt( ) sin(radians), asin( ) cos( ), acos( ) tan( ), atan( )
58
© 2007 D. J. Foreman JS-m57 Some Math Object Properties E LN2, LN10 LN2E, LOG2E PI SQRT2 SQRT1_2 (sqrt of 1/2) ex: Math.PI These are all constants
59
Date Object The Date object is used to work with dates and times. Find out more here!here ©2007 D. J. Foreman JS-58
60
Date object Examples Return today's date and time How to use the Date() method to get today's date. Return today's date and time getTime() Use getTime() to calculate the years since 1970. getTime() setFullYear() How to use setFullYear() to set a specific date. setFullYear() toUTCString() How to use toUTCString() to convert today's date (according to UTC) to a string. toUTCString() getDay() Use getDay() and an array to write a weekday, and not just a number. getDay() Display a clock How to display a clock on your web page. Display a clock ©2007 D. J. Foreman JS-59
61
© 2007 D. J. Foreman JS-m60 Some Misc Methods blur( ) focus( ) select( ) eval( ) to re-call the interpreter parseInt( ) or ParseFloat( ) if var x="10"; y="5"; x+y gives "105" parseInt(x)+parseInt(y) gives 15
62
© 2007 D. J. Foreman JS-m61 Some Useful References "Javascript by Example" (various publishers, if you can find it) "How to Set Up and Maintain a WWW Site", Addison Wesley "Essential Javascript for Web Professionals", Prentice Hall "Essential CSS & DHTML for Web Professionals", Prentice Hall
63
©2007 D. J. Foreman JS-62
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.