CIS 228 The Internet Day 28, 12/13 Review. Alphabet Soup HTML (delineates document structure) HyperText Markup Language CSS (specifies document presentation)

Slides:



Advertisements
Similar presentations
Presenter: James Huang Date: Sept. 26,  Introduction  Basics  Lists  Links  Forms  CSS 2.
Advertisements

HTML – A Brief introduction Title of page This is my first homepage. This text is bold  The first tag in your HTML document is. This tag tells your browser.
Cascading Style Sheets. CSS stands for Cascading Style Sheets and is a simple styling language which allows attaching style to HTML elements. CSS is a.
Cascading Style Sheets Basics. Why use Cascading Style Sheets? Allows you to set up a series of rules for all pages in a site. The series may be changed.
Building a Website: Cascading Style Sheets (CSS) Fall 2013.
1 Pengantar Teknologi Internet W03: CSS Cascading Style Sheets.
CIS 1310 – HTML & CSS 6 Layout. CIS 1310 – HTML & CSS Learning Outcomes  Describe & Apply the CSS Box Model  Configure Float with CSS  Designate Positioning.
CSS(Cascading Style Sheets )
Web Pages and Style Sheets Bert Wachsmuth. HTML versus XHTML XHTML is a stricter version of HTML: HTML + stricter rules = XHTML. XHTML Rule violations:
CS4370/6370 Web Development Cascading Style Sheets (CSS)
Text Properties, Line Box, CSS. Text Properties Properties related to the display of text. Text-align : left, right, center I like FSU!
Cascading Style Sheets SP.772 May 6, CSS Useful for creating one unified look for an entire web site. Helps to seperate style from content. Can.
Web Design & Development Cascading Style Sheets (CSS)
CS134 Web Design & Development Cascading Style Sheets (CSS) Mehmud Abliz.
Using Cascading Style Sheets CSS Structure. Goals Understand how contextual, class and ID selectors work Understand how contextual, class and ID selectors.
Lecture CSS: Cascading Style Sheets. What are Styles? Cascading Style Sheets (CSS) is a style sheet language used to describe the presentation semantics.
3.1 Cascading Style Sheets. Motto Fashions fade, style is eternal. —Yves Saint Laurent.
Computer Sciences Department
School of Computing and Information Systems CS 371 Web Application Programming HTML The language of the Web.
Principles of Web Design 6 th Edition Chapter 4 – Cascading Style Sheets.
CSS Dvijesh Bhatt.
Week 4.  Three ways to apply CSS: Inline CSS Internal style sheets ( header style information) External style sheets.
Tutorial #3 Cascading Style Sheets. Review: Last Class Image sizing Pathnames Project Default Path Relative Path Absolute Path Blackboard Homework Submission.
Cascading Style Sheets CSS. CSS - Structure Declaration block Property: identifies what to change Value: how to change it Selector – example h1{ font-size:
New Perspectives on XML, 2nd Edition Tutorial 5 1 TUTORIAL 5 WORKING WITH CASCADING STYLE SHEETS.
XP New Perspectives on XML Tutorial 5 1 TUTORIAL 5 CSS Tutorial – Carey ISBN
Chapter 12 Cascading Style Sheets: Part II The Web Warrior Guide to Web Design Technologies.
 HTML stands for Hyper Text Mark-up Language. The coding language used to create documents for the World Wide Web  HTML is composed of tags. HTML tags.
Doman’s Sections Information in this presentation includes text and images from
HTML. Basic HTML HTML document – HTML headings – to HTML paragraphs – HTML links – HTML images –
CIS 1315 – Web Development for Educators CIS 1315 HTML Tutorials 3 & 4: Working With CSS.
Introduction to CSS. What is CSS?  Cascading Style Sheets  Used for styling HTML  Also important in javascript and jquery for selectors  External.
 2008 Pearson Education, Inc. All rights reserved Introduction to XHTML.
HTML: Hyptertext Markup Language Doman’s Sections.
XHTML 1.1  Derived from Standard Generalized Markup Language (SGML) of ISO  XHTML concerned primary with content rather than presentation and style 
Lesson 03 // Cascading Style Sheets. CSS Stands for Cascading Style Sheets. We’ll be using a combination of Html and CSS to create websites. CSS is a.
INTRODUCTORY Tutorial 4 Exploring Graphic Elements and Images.
 Cascading Style Sheets (CSS) ◦ Used to specify the presentation of elements separately from the structure of the document.  Inline style ◦ declare.
CSS Class 2 -Add margins to elements on a page. -Set width and height of elements. - CSS shorthand properties for box model. -Style links. -Style tables.
Cascading Style Sheets CSS.  Standard defined by the W3C  CSS1 (released 1996) 50 properties  CSS2 (released 1998) 150 properties (positioning)  CSS3.
1 Web Development CSS (Cascading Style Sheet). 2 1.Setting rules for multiple elements To decrease the amount of typing for setting rules for multiple.
©SoftMoore ConsultingSlide 1 Introduction to HTML: Cascading Style Sheets.
Developing Web Applications with HTML and CSS “Selectors and Properties”
Department of Computer Science, Florida State University CGS 3066: Web Programming and Design Spring
CSS: Cascading Style Sheets Part II. Style Syntax.
Department of Computer Science, Florida State University CGS 3066: Web Programming and Design Spring
CIS 228 The Internet 11/17/11 Of Timers and Cookies.
CIS 228 The Internet 9/20/11 XHTML 1.0. “Quirks” Mode Today, all browsers support standards Compliant pages are displayed similarly There are multiple.
CIS 228 The Internet Day 4, 9/8/11 Getting on the Internet.
CIS 228 The Internet 10/18/11 Grouping XHTML. CSS Selectors Rule: selector-group { property-declaration* } Selector-group: selector *, Selector: simple-selector.
CIS 228 The Internet Day 2, 9/1/11 Hypertext. The Course Instructor: Bowen Alpern Office hour: GI 137-I, 4-5pm Tu.
CIS 228 The Internet 11/1/11 Review HFHTML ch 8-14.
CIS 228 The Internet 12/6/11 Forms and Validation.
Tutorial 3 Designing a Web Page with CSS
Chapter 11 & 12 CSS Style Sheets: Intro. Why CSS? Separate presentation from content – more accessible Less work – can change appearance of whole site.
Internet & World Wide Web How to Program, 5/e Copyright © Pearson, Inc All Rights Reserved.
CIS 228 The Internet Day 1, 8/30. The Course Instructor: Bowen Alpern ● Office hour: 4-5pm Tu (and by appointment)
The Internet Day 4, 9/8/11 Getting on the Internet
Cascading Style Sheets
The Internet 10/11/11 Fonts and Colors
The Internet 10/25/11 XHTML Tables
IS333: MULTI-TIER APPLICATION DEVELOPMENT
The Internet 10/13/11 The Box Model
The Internet Day 8, 9/22 Review HFHTML ch 1 - 7
The Internet 12/8/11 JavaScript Review
The Internet 11/29/11 Functions
The Internet 11/15/11 Handling Data in JavaScript
The Internet 11/22/11 Conditionals and Loops
The Internet 10/27/11 XHTML Forms
The Internet 10/20/11 CSS Layout
Presentation transcript:

CIS 228 The Internet Day 28, 12/13 Review

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

An HTML Document A minimal web page Hello world!

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 & (“&”), < (“ ”), © (“©”)

HTML Character Entities <<<less than >>>greater than &&&ampersand “""double quote '&apos;'apostrophe  non-breaking space Required in content, meaningless in markup (tags) More:

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”)

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

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)

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

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

Hyperlink Examples todo Directions My firetruck page <a href=“ title=“office hour”>My office hour Catch 22

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?)

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)

“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)

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" " HTML 4.01 (strict) <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" " XHTML 1.0 (strict) <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "

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)

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" " > Root element <html xmlns=" xml:lang="en" lang="en" >

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 (< &gt, …) instead

XHTML Grouping Block grouping: div element Cats For Sale Six week old Tabby … Eight week old Siamese … Inline grouping: span element Trotsky arrived

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 )

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

XHTML Form Elements (groups form fields together) (caption for a field set)

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

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)

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”

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 ; }

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]

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

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 “-”

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 }

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 ; }

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

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

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

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

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

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)

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

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

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”

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)

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: #3FE29B = rgb( 63, 226, 155)

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

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

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 )

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

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 ;

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

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

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() { … }

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

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);

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

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;

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

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

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 )

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)

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

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

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”;

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

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”)

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 != == == = 5.14 Explicit conversions ParseInt(“6”) + parseInt(“3”) == == 9 ParseFloat(“3.14”) + 2 == 5.14

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;

innerHTML Property A property of XHTML elements function enterText(el) { Var in = prompt(“enter text”, “”); el.innerHTML = in; }... Enter your HTML text click here

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)?$

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 \\ \. \^ \$ \/ \| \* \+ \? \( \) \{ \} \[ \] (\. ^ $ / | * + ? ( ) { } [ ])

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))*) “]”

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;

Block A sequence of statements packaged into one A block can be used anywhere a statement can { statement 1 statement 2 … statement n }

Conditionals Conditional Expressions cond ? expr 1 : expr 2 Conditional Statements if ( cond ) statement if ( cond ) statement 1 else statement 2

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] ;

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() { … }

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

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);

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

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;

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

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

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 )

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)

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

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

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”;

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

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”)

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 != == == = 5.14 Explicit conversions ParseInt(“6”) + parseInt(“3”) == == 9 ParseFloat(“3.14”) + 2 == 5.14

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;

innerHTML Property A property of XHTML elements function enterText(el) { Var in = prompt(“enter text”, “”); el.innerHTML = in; }... Enter your HTML text click here

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)?$

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 \\ \. \^ \$ \/ \| \* \+ \? \( \) \{ \} \[ \] (\. ^ $ / | * + ? ( ) { } [ ])

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))*) “]”

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;

Block A sequence of statements packaged into one A block can be used anywhere a statement can { statement 1 statement 2 … statement n }

Conditionals Conditional Expressions cond ? expr 1 : expr 2 Conditional Statements if ( cond ) statement if ( cond ) statement 1 else statement 2

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] ;