Upload
lucinda-wilcox
View
262
Download
2
Embed Size (px)
Citation preview
OverviewOverview
Introduction: JavaScript basicsIntroduction: JavaScript basics Expressions and typesExpressions and types ArraysArrays Objects and Associative ArraysObjects and Associative Arrays FunctionsFunctions
JavaScript in a web browserJavaScript in a web browser Invoking JavaScriptInvoking JavaScript JavaScript for accessing and modifying HTML contentJavaScript for accessing and modifying HTML content
Dynamic HTML (DHTML)Dynamic HTML (DHTML)
Sample programsSample programs
Language FundamentalsLanguage Fundamentals
Powerful Object Oriented LanguagePowerful Object Oriented Language
But very different from Java, C#, or C++But very different from Java, C#, or C++
Dynamic and interpretedDynamic and interpreted Can easily define new functions at runtimeCan easily define new functions at runtime
Built in support for regular expressionsBuilt in support for regular expressions
Designed for web browser interactionsDesigned for web browser interactions
Actually a powerful programming language Actually a powerful programming language
Can also be run stand-alone on serverCan also be run stand-alone on server E.g. using RhinoE.g. using Rhino
TypesTypes
BooleanBooleanNumber (just one type for number; c.f. Java Number (just one type for number; c.f. Java which has int, float, double, char, …)which has int, float, double, char, …)ArrayArrayAssociative array / ObjectAssociative array / ObjectFunctionFunctionWhen programming in a given context e.g. a When programming in a given context e.g. a web browserweb browser Many additional types (e.g. HTML Elements and Many additional types (e.g. HTML Elements and
Attributes)Attributes) These are all types of ObjectThese are all types of Object
Expressions (from Flanagan, p. 59)Expressions (from Flanagan, p. 59)
1.71.7 // a numeric literal// a numeric literal “ “JavaScript is Fun!”JavaScript is Fun!” // string literal// string literal truetrue // boolean literal// boolean literal nullnull // the literal null value// the literal null value /java//java/ // a regular expression literal// a regular expression literal { x:2, y:2 }{ x:2, y:2 } // an object literal or associative array// an object literal or associative array [2, 3, 5, 6][2, 3, 5, 6] // an array literal// an array literal function(x) {return x*x}function(x) {return x*x} // function literal// function literal ii // the variable i// the variable i sumsum // the variable sum// the variable sum
Higher Order FunctionsHigher Order Functions
Functions can take other Functions can take other functions as argumentsfunctions as arguments
These are known as These are known as ‘higher-order functions’‘higher-order functions’
This allows for great This allows for great flexibility when flexibility when programmingprogramming
Question:Question: How can similar things be How can similar things be
done with Java?done with Java? There are two ways…There are two ways…
Main FeaturesMain Features
Great for interactive web pagesGreat for interactive web pages Validation, calculation, messagesValidation, calculation, messages
Supported by most full-feature browsersSupported by most full-feature browsers IE, Netscape, Mozilla, Opera, …(though varying support)IE, Netscape, Mozilla, Opera, …(though varying support)
PlacePlace In-lineIn-line Or reference in separate file (good for common functions)Or reference in separate file (good for common functions)
C-like syntaxC-like syntaxAccess to current HTML page via DOMAccess to current HTML page via DOM
(Document Object Model)(Document Object Model)
Weakly typed (c.f. Java’s Strong Typing)Weakly typed (c.f. Java’s Strong Typing) Also called ‘Duck Typing’Also called ‘Duck Typing’
JavaScript ProgrammingJavaScript Programming
Event HandlingEvent HandlingStatements (like C / Java)Statements (like C / Java)Operators Operators Variables global (default)Variables global (default)
Or local (e.g. var x = 1)Or local (e.g. var x = 1)
Types can changeTypes can change Eg. x = 1; x = ‘Hello’Eg. x = 1; x = ‘Hello’
Function definition (decompose problem / reuse)Function definition (decompose problem / reuse)Message AlertsMessage AlertsPage element access with Document Object ModelPage element access with Document Object Model
Views HTML page as a tree of elementsViews HTML page as a tree of elements
Document Object Models (DOMs)Document Object Models (DOMs)
Source of confusion: there are two Source of confusion: there are two document object models: document object models: Legacy DOMLegacy DOMW3C DOM (Levels 1 and 2; details won’t W3C DOM (Levels 1 and 2; details won’t concern us too much here)concern us too much here)They do similar things but in different waysThey do similar things but in different ways Legacy DOM is concise but awkwardLegacy DOM is concise but awkward W3C DOM is less concise, but has consistent W3C DOM is less concise, but has consistent
naming conventionsnaming conventions
Legacy DOMLegacy DOM
Idiosyncratic naming of page elementsIdiosyncratic naming of page elementsYou’ll need a reference guide constantly at hand You’ll need a reference guide constantly at hand to find the correct names to useto find the correct names to use The names of properties do NOT correspond to their The names of properties do NOT correspond to their
HTML namesHTML names
Example:Example: document.anchors[]document.anchors[] an object collection listing all the bookmarks in a an object collection listing all the bookmarks in a
document i.e. document i.e. <a><a> tags with name instead of href tags with name instead of href e.g. e.g. <a name=“Conclusions>Conclusions</a><a name=“Conclusions>Conclusions</a>
other examples include other examples include links[], forms[], links[], forms[], images[]images[]
W3C Document Object ModelW3C Document Object Model
Has consistent naming schemeHas consistent naming scheme
Example methods:Example methods: document.getElementById(“uniqueId”);document.getElementById(“uniqueId”);
Returns a single elementReturns a single element document.getElementsByTagName(“a”);document.getElementsByTagName(“a”);
Returns an array of elements – in this case all the Returns an array of elements – in this case all the <a> tags in the document<a> tags in the document
Hello World ExampleHello World Example
This provides an annoying popup – try it!This provides an annoying popup – try it!<html><html>
<body><body>
<a href="http://www.google.co.uk"<a href="http://www.google.co.uk" onMouseOver="( alert(onMouseOver="( alert( 'Follow link to search on 'Follow link to search on
Google') )">Google') )"> Search on GoogleSearch on Google</a></a>
</body></body>
</html></html>
Invoking JavaScriptInvoking JavaScript
From a URLFrom a URL <a href=“javascript: myFunc()” > Click here to invoke <a href=“javascript: myFunc()” > Click here to invoke
myFunc() </a>myFunc() </a>
From an input event handler (see Hello World From an input event handler (see Hello World example)example)From a page load event <body From a page load event <body onload=“myFunc()”>onload=“myFunc()”>From a timerFrom a timer e.g. setInterval(imageRefresh, 100);e.g. setInterval(imageRefresh, 100); Calls the (user defined) imageRefresh() function Calls the (user defined) imageRefresh() function
every 100 millisecondsevery 100 milliseconds
Handling EventsHandling Events
An event can invoke any valid JavascriptAn event can invoke any valid Javascript One or more statementsOne or more statements Usually a function callUsually a function call
Activated as we saw previously:Activated as we saw previously: <tag attribute1 attribute2 <tag attribute1 attribute2 onEventName="onEventName="javascript code;javascript code;">">
Common EventsCommon Events
An event is given a Name to identify itAn event is given a Name to identify itThe handler for an event gets called when the event The handler for an event gets called when the event occursoccursThe handler takes the form onThe handler takes the form onEventNameEventNameE.g. the code forE.g. the code for onMouseOver onMouseOver is called when the is called when the mouse hovers over a linkmouse hovers over a linkSelectSelect
User enters a form element (onSelect)User enters a form element (onSelect)
ChangeChange Use changes a form element then leaves it (onChange)Use changes a form element then leaves it (onChange)
SubmitSubmit clicks the submit button on a formclicks the submit button on a form (onSubmit)(onSubmit)
Defining FunctionsDefining Functions
function funcName(arg1,arg2, etc) { statements; } function funcName(arg1,arg2, etc) { statements; }
Note:Note: No type information in function signatureNo 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 functionand access with arguments array within function
Example: factorialExample: factorial Recursive calculationRecursive calculation Conditional statementConditional statement Calling from Change eventCalling from Change event Use of document.getElementByIdUse of document.getElementById Use of this.value – gets value of current elementUse of this.value – gets value of current element
Factorial FormFactorial Form<html><html><head><head><script language="JavaScript"><script language="JavaScript">function fac(n)function fac(n){ // do it recursively...{ // 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></script></head></head>
Factorial Form Contd.Factorial Form Contd.<body><body><form><form><p><p><input id="facArg" type="text"<input id="facArg" type="text" onchange=" result = fac(this.value);onchange=" result = fac(this.value);
document.getElementById('facResult').value = document.getElementById('facResult').value = result; " />result; " />
</p></p><p><p><input id="facResult" type="text" /><input id="facResult" type="text" /></p></p></form></form></body></body></html></html>
Invoking JS from HyperlinksInvoking JS from Hyperlinks
JavaScript code can be the destination for JavaScript code can be the destination for a hyperlinka hyperlink
Use: Use: <a href=“javascript: myFunc(‘arg’)”>Click here <a href=“javascript: myFunc(‘arg’)”>Click here
to invoke myFunc(arg)</a>to invoke myFunc(arg)</a>
Example below uses this to dynamically Example below uses this to dynamically change the appearance of a listchange the appearance of a list
Note usage ofNote usage of
In JavaScript function listStyle()In JavaScript function listStyle() document.getElementById(id);document.getElementById(id); setAttribute(“class”, value);setAttribute(“class”, value);
In HTMLIn HTML Function call on hrefFunction call on href Alternative string quotes ‘’ to pass argument:Alternative string quotes ‘’ to pass argument:
listStyle(‘noBullet’);listStyle(‘noBullet’); id=“myList” to identify the listid=“myList” to identify the list
Sorting ExampleSorting Example
Sort Numbers or StringsSort Numbers or Strings
Default: everything converted to a stringDefault: everything converted to a string Provide a comparator to override thisProvide a comparator to override this
Running SortRunning Sort
This was after clicking middle (buggy) sortThis was after clicking middle (buggy) sort
Eval FunctionEval Function
Any String can be interpreted as ‘Live’ Any String can be interpreted as ‘Live’ JavaScript code using the ‘eval’ functionJavaScript code using the ‘eval’ function
Can use this to write a code runnerCan use this to write a code runner
Multi-Window CommunicationMulti-Window Communication
The following simple example illustrates multi-The following simple example illustrates multi-window communicationwindow communication A child window is created, filled with content, and A child window is created, filled with content, and
talks back to parenttalks 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 Note use of window.open() to create a new window (a child window)window (a child window) Then writing to the document object of that windowThen writing to the document object of that window And writing to the parent window (opener)And writing to the parent window (opener)
SummarySummary
Concise – due to weak / dynamic typingConcise – due to weak / dynamic typingDOM gives great power to access / modify DOM gives great power to access / modify HTML pageHTML page See auto Table of Contents Example in LabSee auto Table of Contents Example in Lab
Can look up elements by IDCan look up elements by IDEvent-handlingEvent-handling Makes forms interactiveMakes forms interactive
Good for validation / dialogGood for validation / dialogUse Javascript console (Mozilla) for debuggingUse Javascript console (Mozilla) for debuggingSee also AJAX (Google it)See also AJAX (Google it)