Presentation is loading. Please wait.

Presentation is loading. Please wait.

JavaScript. Overview Introduction: JavaScript basics Expressions and types Expressions and types Arrays Arrays Objects and Associative Arrays Objects.

Similar presentations


Presentation on theme: "JavaScript. Overview Introduction: JavaScript basics Expressions and types Expressions and types Arrays Arrays Objects and Associative Arrays Objects."— Presentation transcript:

1 JavaScript

2 Overview Introduction: JavaScript basics Expressions and types Expressions and types Arrays Arrays Objects and Associative Arrays Objects and Associative Arrays Functions Functions JavaScript in a web browser Invoking JavaScript Invoking JavaScript JavaScript for accessing and modifying HTML content JavaScript for accessing and modifying HTML content Dynamic HTML (DHTML) Sample programs

3 Language Fundamentals Powerful Object Oriented Language But very different from Java, C#, or C++ Dynamic and interpreted Can easily define new functions at runtime Can easily define new functions at runtime Built in support for regular expressions Designed for web browser interactions Actually a powerful programming language Can also be run stand-alone on server E.g. using Rhino E.g. using Rhino

4 Types Boolean Number (just one type for number; c.f. Java which has int, float, double, char, …) Array Associative array / Object Function When programming in a given context e.g. a web browser Many additional types (e.g. HTML Elements and Attributes) Many additional types (e.g. HTML Elements and Attributes) These are all types of Object These are all types of Object

5 Expressions (from Flanagan, p. 59) 1.7 // a numeric literal 1.7 // a numeric literal “JavaScript is Fun!” // string literal “JavaScript is Fun!” // string literal true // boolean literal true // boolean literal null // the literal null value null // the literal null value /java/ // a regular expression literal /java/ // a regular expression literal { x:2, y:2 } // an object literal or associative array { x:2, y:2 } // an object literal or associative array [2, 3, 5, 6] // an array literal [2, 3, 5, 6] // an array literal function(x) {return x*x} // function literal function(x) {return x*x} // function literal i // the variable i i // the variable i sum // the variable sum sum // the variable sum

6 Higher Order Functions Functions can take other functions as arguments These are known as ‘higher-order functions’ These are known as ‘higher-order functions’ This allows for great flexibility when programming Question: How can similar things be done with Java? How can similar things be done with Java? There are two ways… There are two ways…

7 Main Features Great for interactive web pages Validation, calculation, messages Validation, calculation, messages Supported by most full-feature browsers IE, Netscape, Mozilla, Opera, …(though varying support) IE, Netscape, Mozilla, Opera, …(though varying support)Place In-line In-line Or reference in separate file (good for common functions) Or reference in separate file (good for common functions) C-like syntax Access to current HTML page via DOM (Document Object Model) (Document Object Model) Weakly typed (c.f. Java’s Strong Typing) Also called ‘Duck Typing’ Also called ‘Duck Typing’

8 JavaScript Programming Event Handling Statements (like C / Java) Operators Variables global (default) Or local (e.g. var x = 1) Or local (e.g. var x = 1) Types can change Eg. x = 1; x = ‘Hello’ Eg. x = 1; x = ‘Hello’ Function definition (decompose problem / reuse) Message Alerts Page element access with Document Object Model Views HTML page as a tree of elements Views HTML page as a tree of elements

9 Document Object Models (DOMs) Source of confusion: there are two document object models: Legacy DOM W3C DOM (Levels 1 and 2; details won’t concern us too much here) They do similar things but in different ways Legacy DOM is concise but awkward Legacy DOM is concise but awkward W3C DOM is less concise, but has consistent naming conventions W3C DOM is less concise, but has consistent naming conventions

10 Legacy DOM Idiosyncratic naming of page elements You’ll need a reference guide constantly at hand to find the correct names to use The names of properties do NOT correspond to their HTML names The names of properties do NOT correspond to their HTML namesExample: document.anchors[] document.anchors[] an object collection listing all the bookmarks in a document i.e. tags with name instead of href an object collection listing all the bookmarks in a document i.e. tags with name instead of href e.g. Conclusions e.g. Conclusions other examples include links[], forms[], images[] other examples include links[], forms[], images[]

11 W3C Document Object Model Has consistent naming scheme Example methods: document.getElementById(“uniqueId”); document.getElementById(“uniqueId”); Returns a single element document.getElementsByTagName(“a”); document.getElementsByTagName(“a”); Returns an array of elements – in this case all the tags in the document

12 Hello World Example This provides an annoying popup – try it! <html><body> <a href="http://www.google.co.uk" onMouseOver="( alert( onMouseOver="( alert( 'Follow link to search on Google') )"> 'Follow link to search on Google') )"> Search on Google Search on Google</a></body></html>

13 Invoking JavaScript From a URL Click here to invoke myFunc() Click here to invoke myFunc() From an input event handler (see Hello World example) From a page load event From a page load event From a timer e.g. setInterval(imageRefresh, 100); e.g. setInterval(imageRefresh, 100); Calls the (user defined) imageRefresh() function every 100 milliseconds Calls the (user defined) imageRefresh() function every 100 milliseconds

14 Handling Events An event can invoke any valid Javascript One or more statements One or more statements Usually a function call Usually a function call Activated as we saw previously:

15 Common Events An event is given a Name to identify it The handler for an event gets called when the event occurs The handler takes the form onEventName E.g. the code for onMouseOver is called when the mouse hovers over a link Select User enters a form element (onSelect) User enters a form element (onSelect)Change Use changes a form element then leaves it (onChange) Use changes a form element then leaves it (onChange)Submit clicks the submit button on a form(onSubmit) clicks the submit button on a form(onSubmit)

16 Defining Functions function funcName(arg1,arg2, etc) { statements; } function funcName(arg1,arg2, etc) { statements; }Note: No type information in function signature No type information in function signature Can declare a function with no args, then pass it some! Can declare a function with no args, then pass it some! and access with arguments array within function and access with arguments array within function Example: factorial Recursive calculation Recursive calculation Conditional statement Conditional statement Calling from Change event Calling from Change event Use of document.getElementById Use of document.getElementById Use of this.value – gets value of current element Use of this.value – gets value of current element

17 Factorial Form <html><head> function fac(n) { // do it recursively... if (n < 2) { if (n < 2) { return 1; return 1; } else { else { return n * fac(n-1); return n * fac(n-1); }}</script></head>

18 Factorial Form Contd. <body><form><p> <input id="facArg" type="text" onchange=" result = fac(this.value); onchange=" result = fac(this.value); document.getElementById('facResult').value = result; " /> document.getElementById('facResult').value = result; " /></p><p> </p></form></body></html>

19 Form in action

20 Invoking JS from Hyperlinks JavaScript code can be the destination for a hyperlink Use: Click here to invoke myFunc(arg) Click here to invoke myFunc(arg) Example below uses this to dynamically change the appearance of a list

21 List Change Function

22 List Change Usage

23 Note usage of In JavaScript function listStyle() document.getElementById(id); document.getElementById(id); setAttribute(“class”, value); setAttribute(“class”, value); In HTML Function call on href Function call on href Alternative string quotes ‘’ to pass argument: Alternative string quotes ‘’ to pass argument:listStyle(‘noBullet’); id=“myList” to identify the list id=“myList” to identify the list

24 Sorting Example Sort Numbers or Strings Default: everything converted to a string Provide a comparator to override this Provide a comparator to override this

25 Our JavaScript test() function

26 Running Sort This was after clicking middle (buggy) sort

27 Eval Function Any String can be interpreted as ‘Live’ JavaScript code using the ‘eval’ function Can use this to write a code runner

28 HTML for Eval

29 JavaScript Evaluation

30 Eval Screenshot (Firefox)

31 Multi-Window Communication The following simple example illustrates multi- window communication A child window is created, filled with content, and talks back to parent A child window is created, filled with content, and talks back to parent Can be used for Calendar controls etc. Can be used for Calendar controls etc. Note use of window.open() to create a new window (a child window) Then writing to the document object of that window Then writing to the document object of that window And writing to the parent window (opener) And writing to the parent window (opener)

32 JS for Window Creation

33 Invisible HTML for Popup Content

34 Exercise: Explain what happened:

35 Summary Concise – due to weak / dynamic typing DOM gives great power to access / modify HTML page See auto Table of Contents Example in Lab See auto Table of Contents Example in Lab Can look up elements by ID Event-handling Makes forms interactive Makes forms interactive Good for validation / dialog Use Javascript console (Mozilla) for debugging See also AJAX (Google it)


Download ppt "JavaScript. Overview Introduction: JavaScript basics Expressions and types Expressions and types Arrays Arrays Objects and Associative Arrays Objects."

Similar presentations


Ads by Google