Download presentation
Presentation is loading. Please wait.
Published byEgbert Samuel Hensley Modified over 8 years ago
1
CIS 228 The Internet Day 28, 12/13 Review
2
Alphabet Soup HTML (delineates document structure) HyperText Markup Language CSS (specifies document presentation) Cascading Style Sheets XHTML (HTML as an XML sub-language) eXtensible HyperText Markup Language XML eXtensible Markup Language
3
An HTML Document A minimal web page Hello world!
4
HTML Vocabulary Tag – markup (enclosed in angle brackets) Opening tags:,,,,, Closing tags:,,,,, Empty tags:,, Element – a component of a document An empty tag, or Opening tag, matching closing tag, everything in between Attribute – a name value pair in an opening or empty tag id=”end”, src=”photo.jpg”, alt=”my pic”, class=”address”> Character Entity – special characters & (“&”), < (“ ”), © (“©”)
5
HTML Character Entities <<<less than >>>greater than &&&ersand “""double quote '''apostrophe non-breaking space Required in content, meaningless in markup (tags) More:http://www.w3schools.com/tags/ref_entities.asp
6
HTML Elements Opening tag, content, closing tag (or empty tag) Elements Nest (form a document tree) The element is the root Each element is fully contained in a unique parent Two kinds: Block elements (large sections of a document) Inline elements (mostly text) Raw text (e.g. “a mule”) Multiple whitespace chars (“ “, “\t”, “\n”) collapse to a singe space Short sections of text (e.g “a very stupid mule”)
7
Web Vocabulary Web page – the unit of hypertext content stored on a server and displayed by a browser Server – a repository for web pages, which are delivered to browsers upon request Browser – obtains web pages specified (explicitly or implicitly via a hyperlink) by a user and displays their contents to the user Hyperlink – clickable html element that indicates a transition to a web page specified by an attribute in the opening tag of the element Hypertext – text containing one or more hyperlinks
8
Hypertext element specifies a hyperlink Content (the link label) is clickable CSS specifies how this content is displayed Usually underlined and in a distinctive color href attribute specifies a new web page As a path to a file on the same computer, or As URL (Uniform Resource Locator) title attribute is a textual description of the page Suggestion: title attribute should match page's title element id attribute provides a destination for hyperlinks target attributes specifies different window (or tab)
9
URL's Uniform Resource Locator protocol://domain:port/path#fragment Protocol – a scheme for exchanging information http (hypertext transfer protocol), ftp, etc. Domain – identifies a server Port – optional number for the protocol to use Path – specifies a file on the server Fragment – specifies a location within the file The id attribute defines the location
10
Paths Path – sequence of names separated by “/”s The final name in a path specifies a file Fragments “#loc” specify locations within a file Other names specify directories (folders) To go down, specify the name of the child directory To go up, use “..” Examples: trucks.html Second Kings/22/20.html../../../second/cousin/once/removed.html
11
Hyperlink Examples todo Directions My firetruck page <a href=“http:/media.lehman.cuny.edu/~bowen/hour.html” title=“office hour”>My office hour Catch 22
12
The Image Element An inline element that identifies an image to display Tag: (an empty element, no closing tag) src attribute, where to find the image Relative path to a local file, or Uniform Resource Locator alt attribute, textual indication of what the image is width attribute, provides browser with size info height attribute, provides browser with size info Use width (and height) to inform the browser Not to resize a large image (why?)
13
Common Image Formats jpg Variable, lossy data compression Good for photos (lots of colors) gif (depricated ??) Good for logos (small number or colors) Transparency png Newer format with transparency (replacing gif !!) psd Adobe Photoshop format (proprietary)
14
“Quirks” Mode Today, all browsers support standards Compliant pages are displayed similarly There are multiple standards HTML 4, HTML 4.01, XHTML 1.0, XHTML 1.1, … Browsers need to know which standard a page adheres to Browsers still need to support old web pages Each browser does this differently (and slowly) To avoid “quirks” mode DOCTYPE announces the standard your page uses Make sure your page obeys that standard (validate)
15
DOCTYPE On the top line of your html file Only a handfull to choose from Spelling (including capitalization) must be identical HTML 4.01 (transitional) <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> HTML 4.01 (strict) <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> XHTML 1.0 (strict) <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
16
HTML 4.01 Compliance Issues Images need an alt attribute Specify a character encoding Don't leave off end (or start) tag html element required Containing head and body elements (and nothing else) title element required in head element Only block elements nest directly in body or blockquote Block elements cannot be in p or inline elements a elements cannot contain other a elements List elements (ol and ul) only contain list items (li)
17
XHTML 1.0 Strict Well-formed XML (empty elements end “ />”) XML declaration (optional) Document Type Declaration <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd" >http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd Root element <html xmlns="http://www.w3.org/1999/xhtml"http://www.w3.org/1999/xhtml xml:lang="en" lang="en" >
18
Well-formed XML Document needs to contain at least 1 element Unique root element contains whole document Tags must nest properly Empty tags end “/>” Tag names are case sensitive Attribute values must be quoted Characters “ ”, “&”, “'”, and '”' Cannot appear in content Use character entities (< >, …) instead
19
XHTML Grouping Block grouping: div element Cats For Sale Six week old Tabby … Eight week old Siamese … Inline grouping: span element Trotsky arrived
20
XHTML Tables Table – 2 dimensional array of cells (explicit) attribute: summary (must be first child of ) Row – 1 dimensional array of cells (explicit) table row Column – 1 dimensional array of cells (implicit) Cell – a single item (explicit) Attributes: rowspan colspan (e.g. ) table data (e.g. $3.79 ) table heading (e.g. price )
21
XHTML Forms Limited 2-way communication between user & server (Heretofore server supplies information to the user) Browser sends name-value pairs to server application Names are specified by the application Values are supplied by the user Application responds with new web page for browser (Creating server applications beyond this course) Forms structure the interaction Give user “natural” means of supplying information
22
XHTML Form Elements (groups form fields together) (caption for a field set)
23
Form Element action Relative (path to local application) Absolute (path to application on a different site) method post - form data bundled in separate communication Cannot be bookmarked get - form data appended to the URL Size limited Do not use to transmit sensitive data
24
Input Element Types text value (default), size, maxlength radio value (value), checked checkbox value (value), checked submit value (button text) reset value (button text) button value (button text) password value (default), size, maxlength file (value invalid), accept image value (value), src, alt hidden value (default)
25
Attaching CSS to a Web Page Style attribute (on element in ) Value: one or more CSS rules Deprecated Style element (in ) Attribute type=”text/css” Content: one or more CSS rules Link element (empty element in ) Attribute type=”text/css” Attribute rel=”stylesheet” Attribute href=”somepath/file.css”
26
CSS Rules Template: selector { property : value + ; } Selector identifies 0 or more elements in a document Element names (e.g. blockquote, p, q …) Class attribute values (e.g. p.legalese or.legalese) Id attribute values (e.g. p#signature or #signature) Property governs an aspect of element presentation Value specifies a property (e.g. 7px, 7%, red, #777, etc.) Example: p.legalese, #signature { color: #0BEAF0 ; }
27
CSS Selectors Rule: selector-group { property-declaration * ; } Selector-group: selector *, Selector: simple-selector * operator Operator: descendant (“”) | child (“>”) | sibling (“+”) Simple-selector: (universal (“*”|“”) | type) context* (type is an XHTML element name) Context selectors Id-selector: #identifier Class-selector:.identifier Pseudo-class: :identifier (e.g. :link, :visited, :hover, etc.) Attribute-selector: [identifier]
28
Attribute Selectors Distinguish elements having the same name Special cases: class and id attributes XHTML (and HTML) Any element (in ) can have a class attribute At most one element can have any value for an id attribute CSS for class and id attributes p.legalese { color: red ; }.legalese { font-size: small ; } p#signature { font-size: 3em ; } #signature { border: 1px solid #DEAD29
29
Attribute Selectors, continued Match elements based on their attribute [title] elements with a title attribute e.g. li > a[title] [title=UN] matches elements with title UN e.g. p[class=loser] (same as p.loser) [title~=UN] matches element with UN in the title In a value that is a list of identifiers separated by “ ” [lang|=en] matches elements containing en in lang In a value that is a list of identifiers separated by “-”
30
Pseudo Classes and Elements Refer to state not represented in the element tree Pseudo-classe selectors :link, :visited, :hover register the state of hyperlinks e.g. a:link { color: C4C } :first-child selects the first element of its parent e.g. blockquote > p:first-child { indent: 4em } Pseudo-element selectors (must come last) :first-letter, :first-line e.g. p.first-letter { font-size: 5em } :before, :after (not supported by IE) e.g. blockquote:before { content: open-quote }
31
Property Inheritance Some property values are inherited e.g. color, font-family Some are not e.g. border (why?) Elements pass inherited values to their children e.g. em inherits color from p Inheritance can be overridden by explicit assignment e.g. em { color: maroon ; }
32
Determining Property Values What is the value v of property p on element e? Is there a rule that selects e and defines p? Only one? that rule gives v More than one? take the (physically) last one Is p an inherited property? Take the value of p for e's parent Otherwise Default value Multiple style sheets are concatenated together
33
The Cascade Which declaration for property p applies on element e? Concatenate style sheets: Browser defaults User style sheet Applicable author style sheet(s) (in order) Gather declarations whose selectors match the e (If none, check inheritance) If any are “ ! important ”, ignore the rest (You can mark declarations “ ! important ”, but don't!) Ignore all but the most specific declarations The physically last remaining declaration wins
34
Selector Specificity Rules specified by style attributes are most specific If there is one, ignore the rest Id-selectors are most important Ignore rules with less than the most id-selectors Context-selectors are very important Ignore rules with less than the most context-selectors Type selectors are important Ignore rules containing less than the most type-selectors Remember: last remaining rule wins
35
The Box Model Element content is surrounded by (optional) boxes: Padding transparent space Border width style solid double groove outset dotted dashed inset ridge color if not specified, same as content text (element color) Margin transparent space
36
Box Model Properties padding: 10px border: 2px dotted #A84E19 border-width: 2px border-style: dotted border-color: #A84E19 margin: 8em background-image: url(Images/myDucky.png) background-repeat: no-repeat background-position: top center
37
Sides Each box has four sides: top right bottom left (clockwise ordering) Properties of an individual side can be specified border-bottom-style: dotted padding-left: 10% Properties of each side can be specified in turn border-style: none double dotted inherit margin: 2em 5% 30px 6pt padding: 4em 8em (4em 8em) border-width: 3px (3px 3px 3px)
38
Some Fonts Sans-serif Ariel, Verdana, Geneva, Helvetica, “DejaVu Sans” Serif “Times New Roman”, Times, “DejaVu Serif” Monospace “Courier New”, Courier, “DejaVu Sans Mono” Cursive “Comic Sans”, Cartoon, “Apple Chancery” Fantasy Impact, “Last Ninja”, Crush, Papyrus
39
Font Size Keywords: xx-small, x-small, small, medium, large, x-large, xx-large Absolute size: Pixels: 14px Points: 14pt Relative size: Reference character: 1.4em Percentage: 140% Suggestions: Default: use keyword (medium or small) in body rule Otherwise: use relative size measurements
40
Other Text Properties font-weight “bold” or “normal” font-style “italic” (“oblique”) or “normal” text-decoration “underline”, “overline”, “line-through”, “blink”, “none” line-height e.g. 1.6em or 160% text-align “left”, “center”, “right”, “justify”, “inherit”
41
Color Properties background-color: color: Specifying color 17 named colors black, white, red, green, blue, aqua, fuchsia, yellow, etc. Red-Green-Blue triples rgb(255, 127, 63) rgb(100%, 50%, 25$) Hex codes #FF7F3F #963 (= #996633)
42
Deciphering Hex Color Codes Example: #3FE29B Separate into color pairs: 3F E2 9B Replace letters with numbers: 3(15) (14)2 9(11) A->(10) B->(11) C->(12) D->(13) E->(14) F->(15) Multiply first by 16: (48)(15) (224)2 (144)(11) Add: 63 226 155 #3FE29B = rgb( 63, 226, 155)
43
Interpreting Hex Color Codes First 2 digits, red; second 2, green; last 2 blue Round to 3 hex digits: #137FE9 → #18F A=10, B=11, C=12, D=13, E=14, F=15 Largest number: determines main color Big numbers, bright Small numbers, dark Middle number: modifies hue Smallest number: determines greyness Remember: #000 #F00 #FF0 #0F0 #0FF #00F #F0F #FFF #777
44
CSS List Properties Properties of and list-style list-stype-position outside, inside, or inherit list-style-image none or url (e.g. url(images/dimond.jpg) ) list-style-type disc, circle, square, none decimal, lower-alpha, upper-alpha, lower-roman, upper-roman, lower-greek
45
CSS Table Properties Standard CSS properties apply to all table elements color, font, text-align, padding, border, etc. Property for only caption-side: top, bottom, inherit Properties for,,, and border-spacing : length length border-collapse : ( separate, collapse, inherit ) Properties for and align : ( left, right, center, justify, inherit ) valign : ( top, center, bottom, inherit )
46
Normal Flow Block elements Arranged vertically Line break between successive elements Margins overlap Ignore floats Inline elements Arranged horizontally Lines wrap (if they get too long) Margins add Respect float boundaries
47
Floats Floats are removed from the normal flow pushed to the right (or left) of the page at the point they were removed ignored by block elements in the normal flow avoided by inline elements in the normal flow float: right ; Clear property delays a block element until after any float clear: right ;
48
Creating a Sidebar In XHTML 1 Wrap sidebar content in a div element 2 Give the div an id attribute (e.g. id= “sidebar”) 3 Move the div to where sidebar should start In CSS 4 Set width property of the sidebar 5 Set float property of the sidebar 6 Increase margin for content next to the sidebar (optional) 7 Set clear property for content immediately below sidebar
49
The Position Property Absolute top (right, bottom, left) relative to containing positioned element Fixed top (right, bottom, left) relative to viewport (browser window) Relative top (right, bottom, left) relative to element's normal flow position Static Default (normal flow position) Positioned elements may conflict z-index property determines which is visible
50
Attaching JavaScript to XHTML Event attributes of elements (in ) Calls to JavaScript functions Example attribute: onload=“action” element (in ) Attribute: type=“text/javascript” Attribute: src=“cookie.js” (JavaScript in a file) Definitions of JavaScript functions function initialize() { … }
51
Event Attributes onload when the page loads (in opening body tag) onclick when the mouse clicks on an element onfocus when the focus is on an element onblur when the focus leave an element onchange when focus leaves and the value changes
52
Timers One-time 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);
53
JavaScript 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 User defined functions Bundle together small tasks into bigger ones
54
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 fib(n-2) + fib(n-1); return;
55
Comments XHTML comments 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
56
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
57
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., 3.1415, -0.003826, 5498621.0 ) Boolean true or false Object ( e.g., arrays, regular expressions, elements, document )
58
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)
59
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
60
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
61
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”;
62
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
63
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 2*x || x==0)) e.g., s==“done” || ! (name!=“Bowen” && s==“first”)
64
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 2 + 3.14 == 3.14 + 2 == 3.14 + 2.0 = 5.14 Explicit conversions ParseInt(“6”) + parseInt(“3”) == 6 + 3 == 9 ParseFloat(“3.14”) + 2 == 5.14
65
Assignments Form: variable = expression ; Examples: i = i+1; s = “hello world!”; b = isPrime(p) && (q < p || isPrime(q)); x = 3.1415 * 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;
66
innerHTML Property A property of XHTML elements function enterText(el) { Var in = prompt(“enter text”, “”); el.innerHTML = in; }... Enter your HTML text click here
67
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)?$
68
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 \\ \. \^ \$ \/ \| \* \+ \? \( \) \{ \} \[ \] (\. ^ $ / | * + ? ( ) { } [ ])
69
Regular Expressions regular-expression character-set regular-expression regular-expression regular-expression “|” regular-expression regular-expression (“*” | “+” | “?” | “{” int (“,” int)? “}”) “(” regular-expression “)” character-set character (non metacharacter) metacharacter “[” “^”? (character (“-” character))*) “]”
70
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;
71
Block A sequence of statements packaged into one A block can be used anywhere a statement can { statement 1 statement 2 … statement n }
72
Conditionals Conditional Expressions cond ? expr 1 : expr 2 Conditional Statements if ( cond ) statement if ( cond ) statement 1 else statement 2
73
Repetition while 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 ) a[i] = a[i]*a[i] ;
74
Attaching JavaScript to XHTML Event attributes of elements (in ) Calls to JavaScript functions Example attribute: onload=“action” element (in ) Attribute: type=“text/javascript” Attribute: src=“cookie.js” (JavaScript in a file) Definitions of JavaScript functions function initialize() { … }
75
Event Attributes onload when the page loads (in opening body tag) onclick when the mouse clicks on an element onfocus when the focus is on an element onblur when the focus leave an element onchange when focus leaves and the value changes
76
Timers One-time 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);
77
JavaScript 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 User defined functions Bundle together small tasks into bigger ones
78
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 fib(n-2) + fib(n-1); return;
79
Comments XHTML comments 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
80
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
81
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., 3.1415, -0.003826, 5498621.0 ) Boolean true or false Object ( e.g., arrays, regular expressions, elements, document )
82
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)
83
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
84
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
85
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”;
86
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
87
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 2*x || x==0)) e.g., s==“done” || ! (name!=“Bowen” && s==“first”)
88
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 2 + 3.14 == 3.14 + 2 == 3.14 + 2.0 = 5.14 Explicit conversions ParseInt(“6”) + parseInt(“3”) == 6 + 3 == 9 ParseFloat(“3.14”) + 2 == 5.14
89
Assignments Form: variable = expression ; Examples: i = i+1; s = “hello world!”; b = isPrime(p) && (q < p || isPrime(q)); x = 3.1415 * 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;
90
innerHTML Property A property of XHTML elements function enterText(el) { Var in = prompt(“enter text”, “”); el.innerHTML = in; }... Enter your HTML text click here
91
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)?$
92
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 \\ \. \^ \$ \/ \| \* \+ \? \( \) \{ \} \[ \] (\. ^ $ / | * + ? ( ) { } [ ])
93
Regular Expressions regular-expression character-set regular-expression regular-expression regular-expression “|” regular-expression regular-expression (“*” | “+” | “?” | “{” int (“,” int)? “}”) “(” regular-expression “)” character-set character (non metacharacter) metacharacter “[” “^”? (character (“-” character))*) “]”
94
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;
95
Block A sequence of statements packaged into one A block can be used anywhere a statement can { statement 1 statement 2 … statement n }
96
Conditionals Conditional Expressions cond ? expr 1 : expr 2 Conditional Statements if ( cond ) statement if ( cond ) statement 1 else statement 2
97
Repetition while 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 ) a[i] = a[i]*a[i] ;
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.