07 - Web Technologies I

download 07 - Web Technologies I

of 139

Transcript of 07 - Web Technologies I

Web Engineering g g Web Technologies ILecture IX 2nd December 2008 Federico M. Facca

Copyright 2008

STI - INNSBRUCK www.sti-innsbruck.at

Where are we?# 1 2 3 4 5 6 7 8 9 10 11 12 13 14 Date 7th Oct 14h Oct 21st Oct 28th Oct 4th Nov 11th Nov 18th Nov 25th Nov 2nd Dec 9th Dec 6th Jan 13th Jan 20th Jan 27th Jan Title Web Engineering Introduction and Overview Collection Requirements for Web Applications Web Application Modeling Developing Applications with WebML Web Application Architectures I Web Application Architectures II Testing and Usability on the Web Mid Term Exam Web Technologies I Web Technologies II Web Technologies III Web 2.0 Mash-ups Web Application Development Process/ Project Management for Web Applications Final Exam Lecturer F. M. Facca F. M F M. Facca F. M. Facca F. M. Facca F. M. Facca F. M. Facca F. M. Facca F. M. Facca F. M. Facca F. M. Facca F. M. Facca F. Daniel (UNITN) F. M. Facca F. M. Facca2

Web Engineering (703512)

Overview

Introduction HTML & XHTML CSS JavaScript J S i t Wrap-up

Web Engineering (703512)

3

What are the basic ingredients to start to build a Web site

INTRODUCTIONWeb Engineering (703512) 4

Basic Ingredients

Content structuring (and basic presentation) (X)HTML

Business logic (client side) JavaScript

Presentation CSS

with these 3 elements you can start building nice (content static) interfaces for you web applications

Web Engineering (703512)

5

Standards or not Standards?

XHTML and CSS are recommendation from W3C XHTML 1.1 (2.0 is currently a draft) 1 1 (2 0 i tl d ft) http://www.w3.org/MarkUp/

CSS 2.1 (3.0 is under development) http://www w3 org/Style/CSS/ http://www.w3.org/Style/CSS/

JavaScript is not a standard This due to the fact also that at the beginning there was some competition between Sun scripting language and Mircrosoft one An attempt of standardization was made by European p (ECMA), never ), Computer Manufacturers Association ( completed (last version dates back to 1999) http://en.wikipedia.org/wiki/JavaScriptWeb Engineering (703512) 6

How to structure your content in a Web page

HYPERTEXT MARKUP LANGUAGEWeb Engineering (703512) 7

HTML & XHTML

W3C Set Standards Syntax Functionality

HyperText Markup Language (v4.01 1999) Type of More General Language (SGML) Describes Function of Text Using Codes

Extensible HTML (v2.0 2004) Stricter Version of HTML Integrate HTML with XML

Web Engineering (703512)

8

HTML & XHTML

HTML Advantages Platform Portability Speed (size of file) Text File

HTML Disadvantages Rendering Differences E t Extensions i Proprietary Functionality Added by Browsers

XHTML Advantages Resolve Issues with Different HTML Versions

Web Engineering (703512)

9

Syntax

Elements (Tags) Codes that Control Content Appearance Opening/Closing Two-Sided Content

One-Sided

Lowercase

Deprecated Obsolete Elements or Syntax Future Support Not Guaranteed

Web Engineering (703512)

10

Syntax

Comments

White Space p Does Not Render Multiple Spaces Tab, Enter do not Render Use Non breaking Space Non-breaking

Attributes Controls Behavior or Appearance of Element

Web Engineering (703512)

11

Surround All Markup & Text Required Used To Begin & End Every HTML Document g y

Web Engineering (703512)

12

Contains the Document's Header Information Required Important Information p Document Title META Tags

Text Included Does Not Render

Web Engineering (703512)

13

Contains All Content to be Rendered

Attributes leftmargin=number leftmargin number Sets The Left Margin for Page

topmargin=number Sets the Top Margin for the Page

Web Engineering (703512)

14

Styles style=color: colorName | #rrggbb | rgb(#,#,#); Specifies the Color of the Regular Text

style=background-color: colorName | #rrggbb | rgb(#,#,#); Specifies the Background Color

style=background-image: url(filename.ext); Points to Location of Image that is Used as Background Image is Tiled

Web Engineering (703512)

15

Styles style=background-position: horizontal vertical; Specifies the Positioning of the Background Image Can Specify Keywords or Percentages

style=background-repeat: repeat | repeat-x | repeat-y | norepeat; Specifies the Tiling of the Background Image

style=background-attachment: scroll | fi d l b k d h ll fixed; Background Image Scrolls with Page or Acts as Watermark

Web Engineering (703512)

16

Create a Heading Numbered from h1 through h6 h1 is the Top Head Level While h6 is the Bottom

Should not be Used for Text Formatting Convey Page & Content Organization Should be Used in Descending Order

Style style=text-align: left | center | right | justify; Specifies the Alignment of the Heading Text

Web Engineering (703512)

17

&

Inserts Blank Line Before Tag Separates Paragraphs of Text


Causes Text To Break Wherever Tag is Placed

Web Engineering (703512)

18

Lists

Unordered List Renders a Bulleted List Use Where Order or Rank is Unimportant

Style style=list-style-type: disc | square | circle; Changes Style of Bullet Before Item

style=list style image: url(filename.ext); style= list-style-image: url(filename ext); Image Used as Bullet

Web Engineering (703512)

19

Lists

Ordered List Tags Render a Numbered List

Style style=list-style-type: decimal | upper-roman | upper-alpha | style list style type: upper roman upper alpha . . .; Changes Number / Letter Style Before Item

style=list-style-position: inside | outside; style list style position: outside; Changes Wrapped Item Placement

Web Engineering (703512)

20

Lists

Defines an Item in a List

Definition List Defined Term

Definition

Web Engineering (703512)

21

Block Level Elements

Content Indented on Left & Right

Retains All White Space Uses Fixed Width Typeface

Web Engineering (703512)

22

Inline Elements

or Bold

or Italics

Subscripted

Superscripted

Web Engineering (703512)

23

Inline Elements

Used for Applying CSS Classes

Nesting Placing Sets of Tags Within Each Other instead of

Web Engineering (703512)

24

Inserts an Image Into a Document Secondary to Content

Attributes alt=text Provides Alternative Text that Describes the Image IE Displays ALT Text When User Hovers on Image Users Who Surf With Graphics Turned Off Non-graphical Browsers Alt Text is Displayed in Place of Image

Required

Web Engineering (703512)

25

Attributes height=pixels Specifies the Image's Height

src=URL Specifies Location of Image to Place in Web Page Required

width=pixels Specifies the Image's Width

Web Engineering (703512)

26

Style style=float: none | left | right; Place Image on Left / Right & Wrap Text Around It

style=clear: none | left | right; Display Content After Margin is Clear of Floating Elements

style=margin: top# right# bottom# left#; style=border-width: #; y Rendered in Designated Link Color if Image is a Link

Web Engineering (703512)

27

Inserts Plain Line (Horizontal Rule) Across Page Emphasize Divisions & Transitions In Content

Style style=background-color: #RRGGBB | colorname; style=color: #RRGGBB | colorname; style=height: number; t l h i ht b style=width: number;

Web Engineering (703512)

28

Special Characters

& Ampersand

Copyright

Bullet

Registered

Trademark

Web Engineering (703512)

29

Used to Create Links to Other Resources Named Anchor AKA Bookmark Used to Name Specific Locations within a Page id Attribute Defines Destination

Web Engineering (703512)

30

Attributes accesskey=text Character Used as Keyboard Shortcut to Activate Link

coords=X1, Y1, X2, Y2, etc. Coordinates that Define Hot Spot Shape in Image Map

href=URL Specifies Location of Linked Resource Typically Another HTML File Can Also Specify Other Internet Resources Files, E-mail, FTP

Named Anchor or Bookmark URLs are Preceded By #

Web Engineering (703512)

31

Attributes name=text Marks Specific Place Within an HTML Document AKA Named Anchor or Bookmark

rel=text Indicates Relationship Between Documents rel=stylesheet Tells Browser that Linked Document is a Style Sheet

shape=rect | circle | poly | default Specifies Shape of Hot Spot in Image Map

Web Engineering (703512)

32

Attributes title=text Provides Supplemental Information Regarding a Link Behaves Like a Tooltip Should be Less Than 60 Characters

Web Engineering (703512)

33

Example A link to a site. < a href="#P5">A link to paragraph 5 in same document. Paragraph 1 Paragraph 2 Paragraph 3 Paragraph 4 Paragraph 5 content.Web Engineering (703512) 34

Paths

URL (Uniform Resource Locator) Location of Document on Web www.sti-innsbruck.at

Path Location of Document on Server http://www.sti-innsbruck.at/about/team/details/federico-michelefacca/

Web Engineering (703512)

35

Paths

Absolute Exact Location on Server Begins with a / /student/index.htm

Relative Location Relative to Current Document Current Nothing page.htm

Child Separated by / images/background.gif

Parent Two Periods ( ) (..) ../page.htm

Web Engineering (703512)

36

URL

http://www.sti-innsbruck.at/about/team/details.html Communication Protocol http://

Domain www.sti-innsbruck.at

Path /about/team/

Document details.html

Web Engineering (703512)

37

Protocols

Hypertext Transfer Protocol Web Server http://

File Transfer Protocol File Server ftp://

USENET Newsgroup Click Me g p

Web Engineering (703512)

38

Protocols

E-Mail Mailto Send Mail

Can Automatically Include Subject Line mailto:[email protected]?subject=text

Other Options mailto:[email protected][email protected] &[email protected]&subject=subscribe &b t@ d d & bj t b ib &body=Send me your newsletter right away

Web Engineering (703512)

39

Structure to Control Page Layout Structure to Contain & Align Content

Attributes border=# Sets Thickness of Borders Displayed for Table Cells Attribute Set to 0 Will Make Borders Invisible Invisible

Web Engineering (703512)

40

Attributes cellpadding=# Specifies Amount of Space Between Cell & Content in Cell

cellspacing=# Specifies Amount of Space Between Cells

frame=above | below | border | box | hsides | lhs | rhs | void | vsides Specifies Where Borders of Tables & Cells Appear

Web Engineering (703512)

41

Attributes height=# | % Specifies Height of Table in Pixels or Percentage of Window

rules=all | cols | groups | none | rows Specifies Where Gridlines Appear in a Table

valign=top | bottom | middle Specifies Vertical Alignment of Text in Cells

width=# | % Specifies Width of Table in Pixels or Percentage of Window

Web Engineering (703512)

42

Defines Groups of Table Columns for Formatting Only Valid Inside

Attributes align=left | center | right | justify | char Specifies Horizontal Alignment of Contents in Column Group

char=character char= character Specifies Character to Use to Align Text On

Web Engineering (703512)

43

Attributes span=# Specifies Number of Columns Should Span

valign=top | middle | bottom | baseline Specifies Vertical Alignment of Contents in

width=# | % Specifies Width of Each Column in 0* - Column Width Should be Minimum Width

Web Engineering (703512)

44

Defines One or More Columns of Table for Formatting Only Valid Inside or

Attributes align=left | center | right | justify | char Specifies Horizontal Alignment of Contents in Table Column

char=character char= character Specifies Character to Use to Align Text On

Web Engineering (703512)

45

Attributes span=# Specifies Number of Columns the Column Should Span

valign=top | middle | bottom | baseline Specifies Vertical Alignment of Contents in Table Column

width=# | % Specifies Width of Column 0* - Column Width Should be Minimum Width

Web Engineering (703512)

46

&

Defines a Row in a Table

Defines Table Data (a Cell) in a Row Table Data Cells Must Only Appear Within Table Rows Closing Tag Must Appear on Same Line as Content Otherwise Gapping May Occur

Web Engineering (703512)

47

Attributes colspan=# Specifies How Many Columns the Cell Overlaps

rowspan=# Specifies How Many Rows the Cell Overlaps

Web Engineering (703512)

48

&

Specifies the Table Header for a Row Identical to Table Data Cells Except: Cells Contents are Bolded Cells Contents are Centered

Attaches a Caption to a Table

Web Engineering (703512)

49

Example

Web Engineering (703512)

50

How to make your Web page good looking

CASCADE STYLE SHEETWeb Engineering (703512) 51

History of CSS

Initial Proposal for CSS Released in 1994 by Hakon Lie of CERN

World Wide Web Consortium (W3C) Founded in 1994 as a Web Standards Organization

CSS1 (96) 50 Properties www.zvon.org/xxl/css1Reference/Output/index.html

CSS2 (98) 70 Additional Properties www.zvon.org/xxl/css2Reference/Output/index.html

Web Engineering (703512)

52

CSS Basics

Style Rules Determines Style Characteristics for an HTML Element Selector Determines Element to Which Rule is Applied

Declaration Details the Exact Property Values Property Q alit or Characteristic (e g Color) Quality (e.g.,

Value Specification of Property (e.g., Blue)

Style Sheet y Set of Style Rules

Web Engineering (703512)

53

CSS Basics

Style Rule Syntax

Web Engineering (703512)

54

Combining CSS & HTML Inline Modify the Appearance of a Particular Element Style Attribute

Embedded Applied To An Entire Document Redefines All Occurrences of a Particular Element Uses in

Linked External File of Declarations Available to an Entire Site ASCII File with an Extension of .css

Web Engineering (703512)

55

Inline Style Defines a Style for a Single Element Generally Used to Override a Style Set at a Higher Level Only Affects One Instance of an Element

Syntax

Web Engineering (703512)56Embedded Style Always Contained in the Generally Used to Override a Style Set at a Higher Level Only Affects the Document in Which it Resides Syntax selector {declarations} type=text/css> h1 {color:green; font-family:sans-serif;} b {color:yellow; background-color:green;} Web Engineering (703512)57Linked Style External Style Sheet Always Contained in the Text Document that Contains Style Rules Allows Specification of Rules for Multiple Documents p p Does Not Contain HTML Code rel stylesheet href master css SyntaxWeb Engineering (703512)58Cascading Determines Which Rules are Assigned to Elements Weight Assignment Based on Four Variables: Use of the !Important Keyword Origin of the Rule Specificity of the Selector Order of the Rule in the Style SheetWeb Engineering (703512)59Cascading Rule Weight with the !Important Keyword Allows User to Override Authors Style Setting For Particular Element Improves Accessibility of Documents p y Gives Control to Users with Special RequirementsRule Weight by Origin Cascading Order of Precedence:1. Rules From Authors Style Sheet 2. 2 Rules From User s Style Sheet Users 3. Rules From Browsers Style SheetWeb Engineering (703512)60Cascading Rule Weight by Specificity Rules with More Specific Selectors Take Precedence Over Rules with Less Specific Selectors Rule Weight by Order g y Based on Order of Rule within Style Sheet Rules Listed Later Take Precedence Over Those Listed EarlierWeb Engineering (703512)61Inheritance Parent Element that Contains Another Element Child Element within Another Element Inheritance CSS Rules Inherit from Parent to Child Elements Based on Hierarchical Structure of DocumentsWeb Engineering (703512)62Basic Selection Type Selectors Selector Determines Element to which Declaration is Applied Style Sheet Examples: h2 {color: red;} p {font-size: 10 pt;}Web Engineering (703512)63Basic Selection Grouping Selectors Set the Same Declaration for Multiple Selectors Syntax: h1 {color: red;} { ;} h2 {color: red;} or h1, h2 {color: red;}Web Engineering (703512)64Basic Selection Combining Declarations Multiple Declarations May be Stated for Same Selector Syntax: p{ {color: blue;} ;} p {font-size: 12pt;} or p {color: blue; font-size: 12pt;}Web Engineering (703512)65Basic Selection Descendant Selector AKA Contextual Selectors Based on Hierarchical Structure of Elements in Document Syntax: b i {color: #336699; background-color: #000000;} Does Not Apply to i bWeb Engineering (703512)66Advanced Selection id Attribute Selector Applied to Onl ONE Only Unique Element in a Document Core Attribute that can be Applied to Any HTML Element Web Engineering (703512) Syntax:Advanced Selection class Attribute Selector Enables Application of Rule to Selected Element(s) Core Attribute that can be Applied to Any HTML Element Syntax: Text in red with a 30 pixel margin class=quote>Text May be Restricted to a Specific Element Type h1.quote {color: red; margin: 30px;}Web Engineering (703512) 68Advanced Selection Block Level Element Used to Contain Other HTML Elements Displayed Discretely from the Rest of the Document p y y Paragraph Breaks Added Before and After Contents Inline Element Used to Contain Other HTML Elements Used within Text BlocksWeb Engineering (703512)69Advanced Selection Pseudo-Class Selectors Select Elements Based on Characteristics Other Than Name Link Pseudo-Classes :link Allow Modification of Style Characteristics for Unvisited Links :link {color: green;} :visited Allow Modification of Style Characteristics for Visited Links :visited {color: green;}Web Engineering (703512)70Advanced Selection Pseudo-Class Selectors Dynamic Pseudo-Classes Apply Styles to an Element Based on Users Actions :hover A li St l Wh U Applies Style When User M Mouses O Over El Element t :active Applies Style When User Activates Element :focus Applies Style When Element is Accepting User InputWeb Engineering (703512)71Advanced Selection Pseudo-Elements Selectors Modify Aspects of Document Not Classified by Elements :first-letter Apply Style Rules to the First Letter of Any Block-level Element Initial Capitals Drop CapitalsWeb Engineering (703512)72Advanced Selection Pseudo-Element Selectors :first-letterWeb Engineering (703512)Advanced Selection Pseudo-Element Selectors :first-line Apply Style Rules to the First Line of Any Block-level ElementWeb Engineering (703512)74Advanced Selection Child Selector > Apply Style Rules to Child Elements of Any Parent div > blockquote {font-weight: bold;}Web Engineering (703512)75Advanced Selection First Child :first-child Apply Style Rules to the First Child Element of a Parent div > p:first-child {font-weight: bold;}Web Engineering (703512)76Advanced Selection Adjacent Sibling + Apply Style Rules to Elements that Share the Same Parent Are Adjacent in the CodeWeb Engineering (703512)77Fonts Measurement Units Absolute Units Specify a Fixed Value Cannot be Scaled to Client Display Use Only When Measurements of User Medium are Known Relative Units Enables Scalable Web Pages Adapt to Different Display Types & Sizes Recommended Method for Web Page DesignWeb Engineering (703512)78Fonts Measurement UnitsWeb Engineering (703512)79Font Propertiess Styles style=font-family: fonts; Allows Specification of Font Family Names Generic Font Families Allows Greater Portability A All G t P t bilit Across Pl tf Platforms Serif Traditional Letter Form (e.g., Times) Sans-serif Block Letters, Have no Serifs (e.g., Arial) Monospace Fixed-width Every Letter has Same Horizontal Width Cursive Resembles Handwriting (Limited Support) Fantasy Primarily Decorative (Limited Support)Web Engineering (703512)80Font Properties Styles style=font-family: fonts; Specific Font Families Allows Specification of Particular Font-family Garamond Impact Garamond, User Must Have Font Installed on Machine If not, Browser Will Supply Default Example: style=font-family:Web Engineering (703512)81Font Properties Styles style=font-family: fonts; Specifying Font Substitution Allows Specification of Alternate Fonts Uses Comma Separated List Browser Scans List for First Installed Font Otherwise, Browser Supplies Default Generic Font-family Names can be Used Example: Web Engineering (703512)82Font Properties Styles st le font si e si e | ke ord | %; style=font-size: size keyword % Absolute Keywords xx-small x-small small medium large x large x-large xx-largeWeb Engineering (703512)Font Properties Styles style=font-size: size | keyword | %; Relative Keywords Smaller | Larger Example Parent Elements Size is Large Current Elements Size is Set to Larger Result is that the Current Font Size will be X-large Percentage Example 50%, 150%, 200%Web Engineering (703512)Font Properties Styles style=font-style: normal | italic | oblique; style=font-variant: normal | small-caps; style=font-weight: normal | bold | bolder | lighter | #; y g g ; # = 100 900 in Increments of 100 400 = Normal 700 = BoldWeb Engineering (703512)Font Properties Font Shortcut Allows Specification of Properties in a Single Statement Font-size & Font-family Required Must be in Order Line-height Must be Preceded by / Example: style=font: bold; >Web Engineering (703512)86Text Properties Styles st le line height # | % style=line-height: %; AKA Leading style=letter-spacing: normal | #; #; AKA Kerning style=word-spacing: normal | #; #; AKA TrackingWeb Engineering (703512)Text Properties Styles style=text-indent: # t l t t i d t #; Allows Specification Amount of Indentation of First LineWeb Engineering (703512)Text Properties Styles style=text-decoration: none | underline | overline | linet l t t d ti d li li li through | blink; style=text-transform: capitalize | uppercase | lowercase | style= text-transform: none;Web Engineering (703512)Text Properties Styles style=vertical-align: b t l ti l li baseline | sub | super | t | textli b top t t top | middle | bottom | text-bottom | % | #;Web Engineering (703512)Visual Formatting Model Three Element Display Type Categories Block (e.g., Paragraphs) Contain Inline Boxes that Contain Element Content I li Inline Contain Content within the Block-level Elements Do not Form New Blocks of Content List-item Creates Surrounding Container and List-item Inline Boxes display: block | inline | list-item | noneWeb Engineering (703512)91Box Model Describes Rectangular Boxes that Contain Content Each Block-level Element is Displayed as a Box Each Content Box can have Margins, Borders, & PaddingWeb Engineering (703512)92Margin Properties margin: # | % Shorthand Propert Sets All Fo r Indi id al Margins Property Four IndividualWeb Engineering (703512)Margin Properties margin-left | margin-right | margin-top | marginbottom: # | % Negative margins can be set to achieve special effectsWeb Engineering (703512)Padding Properties padding: # | % Shorthand Property Sets All Four Individual Paddings Same Format as Margin padding-left | padding-right | padding-top | padding-bottom: # | %Web Engineering (703512)Border Properties border: style width color Shorthand Property Sets All Four Individual Borders Same Format as Margin gWeb Engineering (703512)Border Properties border-style: keyword K Keywords d none dotted dashed solid double groove ridge inset outset t tWeb Engineering (703512)Border Properties border-width: thin | medium | thick | # border-color: valueWeb Engineering (703512)Special Box Properties width: # | % Sets Horizontal Width of a Containing Box height: # | % Sets Vertical Height of a Containing Box float: left | right | none g Sets Position of an Element to Left/Right of Parent Element clear: none | left | right | both Controls Flow of Text Around Floated ElementsWeb Engineering (703512)Special Box Properties float & clearWeb Engineering (703512)Background Properties background-color: colorname | #Web Engineering (703512)Background Properties background-image: url(imagename.gif)Web Engineering (703512)Background Properties background-repeat: repeat | repeat-x | repeat-y | no-repeat no repeatWeb Engineering (703512)Background Properties background-position: % | length | keywordWeb Engineering (703512)Background Properties background-attachment: scroll | fixedWeb Engineering (703512)List Properties list-style-type: disc | circle | square | decimal | decimal-leading-zero lower-roman upper-roman decimal leading zero | lower roman | upper roman | lower-greek | lower alpha | lower-latin | upper-alpha | upper-latin | hebrew | armenian | georgian | cjkideographic | hiragana | katakana | hira-ganairoha | katakana-iroha | none Default = disc Allows Customization of the List Marker Syntax:ul {list-style-type: circle;}Web Engineering (703512)106List Properties list-style-typeWeb Engineering (703512)List Properties list-style-image: url(filename.ext) All Allows U of I Use f Image as Li t M k List Marker Syntax:ul {list-style-image: url(paw.gif);} { y g (p g );}Web Engineering (703512)108List Properties list-style-position: inside | outside Default = inside Allows Placement of the List Marker Syntax:ul {list-style-position: outside;}Web Engineering (703512)109Positioning Properties position: type position size type = static | relative | absolute | fixed position = top | left | bottom | right size = height | widthWeb Engineering (703512)110Positioning Properties div {position:absolute; left:130px; top:100px;}Web Engineering (703512)Positioning Properties div {position:absolute; left:130px; top:100px; width: 100px;}Web Engineering (703512)Positioning Properties visibility: visible | hidden Specifies Whether an Element is Displayed or Hidden z-index: auto | # Specifies an Elements Stacking LevelWeb Engineering (703512)113ExampleWeb Engineering (703512)114How to add some business logic to your Web pageJAVASCPRIPTWeb Engineering (703512) 115Whats a Scripting Language? Language used to write programs that compute inputs t another language processor i t to th l One language embedded in another Embedded JavaScript computes HTML input to the browser Shell scripts compute commands executed by the shell Common characteristics of scripting languages String processing since commands often strings Simple program structure, define things on the fly Flexibility preferred over efficiency, safety Is lack of safety a good thing? (Example: JavaScript used for Web applications)Web Engineering (703512)JavaScript History Developed by Brendan Eich at Netscape Scripting language for Navigator 2 Later standardized for browser compatibility ECMAScript Edition 3 (aka JavaScript 1 5) 1.5) Related to Java in name only Name was part of a marketing deal Various implementations available SpiderMonkey C implementation (from Mozilla) Rhino Java implementation (also from Mozilla)Web Engineering (703512)Common Uses of JavaScript Form validation Page embellishments and special effects Navigation systems Basic B i math calculations th l l ti Dynamic content manipulation Sample applications Dashboard widgets in Mac OS X, Google Maps, Philips universal remotes, Writely word processor, hundreds of others othersWeb Engineering (703512)Example 1: Add Two Numbers var num1 num2 sum num1, num2, num1 = prompt("Enter first number") num2 = prompt("Enter second number") sum = parseInt(num1) + parseInt(num2) I t( 1) I t( 2) alert("Sum = " + sum) Web Engineering (703512)Example 2: Browser Events Mouse event causes page-defined page defined function function whichButton(event) { to be called if (event.button==1) { alert("You clicked the left mouse button!") } else { alert("You clicked the right mouse button!") }} / i t Web Engineering (703512)Example 3: Page Manipulation Some possibilities createElement(elementName) createTextNode(text) appendChild(newChild) pp ( ) removeChild(node) Example: add a new list itemvar li t = document.getElementById('t1') list d t tEl tB Id('t1') var newitem = document.createElement('li') var newtext = document.createTextNode(text) list.appendChild(newitem) newitem.appendChild(newtext)Web Engineering (703512)Language Basics JavaScript is case sensitive onClick, ONCLICK, are HTML, thus not case-sensitive Statements terminated by returns or semi-colons x = x+1; same as x = x+1 Blocks of statements enclosed in { } Variables Define using the var statement Define implicitly by its first use, which must be an assignment Implicit defn has global scope, even if occurs in nested scope!Web Engineering (703512)JavaScript Primitive Datatypes Boolean: true and false Number: 64-bit floating point Similar to Java double and Double No integer type Special values NaN (not a number) and Infinity String: sequence of zero or more Unicode chars No separate character type (just strings of length 1) Literal strings using ' or " characters (must match) Special objects: null and undefinedWeb Engineering (703512)Objects An object is a collection of named properties Think of it as an associative array or hash table Set of name:value pairs objBob = { j {name: Bob", g , grade: 'A', level: 3}; , }; Play a role similar to lists in Lisp / Scheme New members can be added at any time objBob fullname = 'Robert'; objBob.fullname Can have methods Can refer to thisWeb Engineering (703512)Functions Functions are objects with method called ( ) A property of an object may be a function (=method) function max(x,y) { if (x>y) return x; else return y;}; max.description = return the maximum of two arguments; Local declarations may appear in function body Call can supply any number of arguments functionname.length : # of arguments in definition functionname.arguments.length : # arguments in call Basic types are passed by value, objects by reference A Anonymous functions f ti (function (x,y) {return x+y}) (2,3);Web Engineering (703512)Examples of Functions Curried functions function CurriedAdd(x) { return function(y){ return x+y} }; g = CurriedAdd(2); g(3) V i bl number of arguments Variable b f tfunction sumAll() { var total=0; for (var i 0; i< sumAll arguments length; i++) i=0; sumAll.arguments.length; total+=sumAll.arguments[i]; return(total); } sumAll(3,5,3,5,3,2,6)Web Engineering (703512)Anonymous Functions Anonymous functions very useful for callbacks setTimeout(function() { alert("done"); }, 10000) Evaluation of alert("done") delayed until function call Simulate blocks by function definition and callvar u = { a:1, b:2 } var v = { a:3, b:4 } (function (x,y) { (f ti ( ) var tempA = x.a; var tempB =x.b; // local variables x.a=y.a; x.b=y.b; y.a=tempA; y.b-tempB }) (u,v) // Works because objs are passed by refWeb Engineering (703512)Basic Object Features Use a function to construct an object j function car(make, model, year) { this.make = make; this.model this model = model; this.year = year; } Objects have prototypes, can be changed var c = new car(Ford,Taurus,1988); car.prototype.print = function () { return this year + + this.make + + this.model;} this.year this make this model;} c.print();Web Engineering (703512) slide 128JavaScript in Web Pages Embedded in HTML page as element JavaScript written directly inside element alert("Hello World!") Linked file as src attribute of the element