Presentation is loading. Please wait.

Presentation is loading. Please wait.

The Internet 12/8/11 JavaScript Review

Similar presentations


Presentation on theme: "The Internet 12/8/11 JavaScript Review"— Presentation transcript:

1 The Internet 12/8/11 JavaScript Review
CIS 228 The Internet 12/8/11 JavaScript Review

2 Attaching JavaScript to XHTML
Event attributes of elements (in <body>) Calls to JavaScript functions Example attribute: onload=“action” <body onload=”initialize()”> <script> element (in <head>) Attribute: type=“text/javascript” Attribute: src=“cookie.js” (JavaScript in a file) Definitions of JavaScript functions <script type=”text/javascript”> function initialize() { … } </script>

3 Event Attributes onload when the page loads (in opening body tag)
<body onload=“initialize()”> onclick when the mouse clicks on an element <input type=“button” onclick=“validate(this)” /> onfocus when the focus is on an element <input type=“text” onfocus=“setDefault(this)” /> onblur when the focus leave an element <input type=“text” onblur=“notEmpty(this)” /> onchange when focus leaves and the value changes <input type=“text” onchange=“refigure(this)” />

4 Timers One-time timers Repeating timers Canceling repeating timers
setTimeout(what, when); what – action to take (e.g., “alert('wake up!');”) when – time delay in milliseconds (e.g., 5 * 60 * 1000) Repeating timers const timerId = setInterval(what, when); what – action to take when – time between repeated actions Canceling repeating timers clearInterval(timerId);

5 JavaScript Functions Built in functions Example User defined functions
Reusable chunks of code that accomplish common tasks Built in functions alert('hello world'); Displays text in a pop up window prompt('first message', 'second message'); Solicits data from user Example <body onload=“alert('hello world');”> User defined functions Bundle together small tasks into bigger ones

6 User-Defined Functions
Declaration: function name (param * ,) block function fib (n) { if (n<=1) return 1; return fib(n-2) + fib(n-1); } Call (expression or statement): name (args * ,) var x = fib(17)/3; complainToUser(x, “ is not a number!”); Return statement: return expression? ; return;

7 Comments XHTML comments CSS comments JavaScript comments
<!--This is an HTML comment--> CSS comments /* This is a CSS comment */ JavaScript comments // text to the end of line ignored /* Multi-line comment */ Temporary comments are useful for debugging

8 JavaScript Identifiers
Identifiers name functions and locations Rules: 1 or more characters First character must be: letter or “_” or “$” All characters must be: letter or digit or “_” or “$” Spaces and other special characters are not allowed Camel case convention (for variables) thisIsACamelCaseVariableId Upper case convention (for constants) THIS_IS_AN_UPPER_CASE_CONSTANT_ID

9 JavaScript Data Types String (text)
(e.g. “this is a string”, 'so is this', 'don\'t worry') Number Integer (e.g., 23, 0, -37) Decimal (e.g., , , ) Boolean true or false Object (e.g., arrays, regular expressions, elements, document)

10 The document Object Can appear on either side of an assignment
document (the root of the “DOM” object) .getElementById(“x”) (the element with id=“x”) .sytle (the style attribute of that element) .height (the height of the element) .color (the color of the element) .getElementById(“i”) (and the element is img) .src (the URL of the file containing an image) .getElementById(“f”)(and the element is a form field) .value (the value entered in the field)

11 JavaScript Variables Associate a name with a value
Variable – the value may change Declaration: var s = “The user name is ”; Declarations should usually initialize their variables Use: var userName = prompt(s+“?”, ””); Definition: s = s + userName; Values have types; locations do not! var x = 17; (x is a number) x = “” + x; (x is a string) Arrays are objects (values) that contain variables

12 Arrays A collection of variables with the same name
differentiated by an index (key) Declaration: var a = new array(5); // size, 5, optional var b = [“red”, “yellow”, “blue”]; Use: var c = “color: ” + b[2]; a[2] = (a[1] + a[3]) / 2; Size: a.length

13 Associative Arrays Array - collection of variables with the same name
differentiated by an index (key) Keys can be Strings as well as integers. var atomicNumber = new Array(); atomicNumber[“hydrogen”] = 1; atomicNumber[“carbon”] = 6; atomicNumber[“oxygen”] = 8; Var ratio = 64 / atomicNumber[“zinc”]; Form element maps field names to the fields myForm[“zipcode”] = “10468”;

14 Cookies Medium-term persistent storage for small values
List of name-value pairs (total size is browser dependent) Name is an identifier Value is a String Expiration date Helper functions (cookie.js) writeCookie(name, value, days); readCookie(name); eraseCookie(name); Not all browsers support cookies Navigator.cookiesEnabled

15 JavaScript Expressions
String operator: + (concatination) e.g., s + userName, “Bowen” + “ ” + “Alpern” Numeric operators: +, -, *, /, % e.g., 3+4, 3-4, 3*4, 3/4, 3%4, 3.14*r*r/2 Comparison operators: ==, !=, <, <=, >, >= e.g., 3+4 != 8, 4/2 == 2, userName == “malcolmX” Boolean operators: !, &&, || e.g., !done && ((3*x+7<21 || 5>2*x || x==0)) e.g., s==“done” || !(name!=“Bowen” && s==“first”)

16 JavaScript Conversions
Error values: undefined – uninitialized locations (always initialize) NaN – not a number (e.g., 'sam' / 3 == NaN) Automatic conversions “12” / “6” == “12” / 6 == 12 / “6” == 12 / 6 == 2 “6” + “3” == “6” + 3 == 6 + “3” == “63” == 63 != 6 + 3 == == = 5.14 Explicit conversions ParseInt(“6”) + parseInt(“3”) == == 9 ParseFloat(“3.14”) + 2 == 5.14

17 Assignments Form: variable = expression ; Examples: i = i+1;
s = “hello world!”; b = isPrime(p) && (q < p || isPrime(q)); x = * gcd(15, 33); a[i] = “seat ” + i; var j = i*(i-1)/2; var v = document.getElementById(s).value; document.getElementById(s).value = 99*v;

18 innerHTML Property A property of XHTML elements
<script type= “text/javascript”> function enterText(el) { Var in = prompt(“enter text”, “”); el.innerHTML = in; } </script> ... <h2>Enter your HTML text</h2> <p onclick=“enterText(this)”>click here</p>

19 Regular Expression Examples
Identifier ^[a-zA-Z_$][a-zA-Z0-9_$]*$ Camel case identifier ^[a-z]+([A-Z][a-z]*)*$ Zipcode ^\d\d\d\d\d$, ^\d{5}$, ^[0-9]{5}$ Date ^1?\d\/\d?\d\/(\d\d|\d\d\d\d)$ Time ^1?\d(:[0-5]\d)?((a|p)m)?$

20 Metacharacters . any character except newline \n newline \d any digit
\w any letter or digit \s whitespace (space, tab, newline, etc.) \D \W \S (not a digit, not a letter or digit, not whitespace) ^ the beginning of a string $ the end of a string \\ \. \^ \$ \/ \| \* \+ \? \( \) \{ \} \[ \] (\ . ^ $ / | * + ? ( ) { } [ ])

21 Regular Expressions regular-expression character-set
regular-expression regular-expression regular-expression “|” regular-expression regular-expression (“*” | “+” | “?” | “{” int (“,” int)? “}”) “(” regular-expression “)” character (non metacharacter) metacharacter “[” “^”? (character (“-” character))*) “]”

22 Using Regular Expressions
Regular expression objects var hatpat = new RegExp(hat, modifiers); var zipcode = /^\d{5}$/; Modifiers (optional) i ignore case m multiline match Use regularExpression.test(text) (true, if text contains a match to patten) if (hatpat.test(“this or that”)) return;

23 Block A sequence of statements packaged into one
A block can be used anywhere a statement can { statement1 statement2 statementn }

24 Conditionals Conditional Expressions Conditional Statements
cond ? expr1 : expr2 Conditional Statements if ( cond ) statement statement1 else statement2

25 Repetition while loops for loops while ( cond ) statement
var i=0 ; while (i<a.length) { a[i] = a[i]*a[i] ; i = i+1 ; } for loops for ( init ; cond ; inc ) statement for ( var i=0 ; i<a.length ; i = i+1 )


Download ppt "The Internet 12/8/11 JavaScript Review"

Similar presentations


Ads by Google