350 likes | 534 Views
Overview. Introduction: JavaScript basicsExpressions and typesArraysObjects and Associative ArraysFunctionsJavaScript in a web browserInvoking JavaScriptJavaScript for accessing and modifying HTML contentDynamic HTML (DHTML)Sample programs. Language Fundamentals. Powerful Object Oriented La
E N D
1. JavaScript CC292
Web Application Programming
Simon M. Lucas
2. Overview Introduction: JavaScript basics
Expressions and types
Arrays
Objects and Associative Arrays
Functions
JavaScript in a web browser
Invoking JavaScript
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
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
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)
These are all types of Object
5. Expressions (from Flanagan, p. 59) 1.7 // a numeric literal
“JavaScript is Fun!” // string literal
true // boolean literal
null // the literal null value
/java/ // a regular expression literal
{ x:2, y:2 } // an object literal or associative array
[2, 3, 5, 6] // an array literal
function(x) {return x*x} // function literal
i // the variable i
sum // the variable sum
6. Higher Order Functions Functions can take other functions as arguments
These are known as ‘higher-order functions’
This allows for great flexibility when programming
Question:
How can similar things be done with Java?
There are two ways…
7. Main Features Great for interactive web pages
Validation, calculation, messages
Supported by most full-feature browsers
IE, Netscape, Mozilla, Opera, …(though varying support)
Place
In-line
Or reference in separate file (good for common functions)
C-like syntax
Access to current HTML page via DOM
(Document Object Model)
Weakly typed (c.f. Java’s Strong 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)
Types can change
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
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
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
Example:
document.anchors[]
an object collection listing all the bookmarks in a document i.e. <a> tags with name instead of href
e.g. <a name=“Conclusions>Conclusions</a>
other examples include links[], forms[], images[]
11. W3C Document Object Model Has consistent naming scheme
Example methods:
document.getElementById(“uniqueId”);
Returns a single element
document.getElementsByTagName(“a”);
Returns an array of elements – in this case all the <a> 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(
'Follow link to search on Google') )">
Search on Google
</a>
</body>
</html>
13. Invoking JavaScript From a URL
<a href=“javascript: myFunc()” > Click here to invoke myFunc() </a>
From an input event handler (see Hello World example)
From a page load event <body onload=“myFunc()”>
From a timer
e.g. setInterval(imageRefresh, 100);
Calls the (user defined) imageRefresh() function every 100 milliseconds
14. Handling Events An event can invoke any valid Javascript
One or more statements
Usually a function call
Activated as we saw previously:
<tag attribute1 attribute2 onEventName="javascript code;">
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)
Change
Use changes a form element then leaves it (onChange)
Submit
clicks the submit button on a form (onSubmit)
16. Defining Functions function funcName(arg1,arg2, etc) { statements; }
Note:
No type information in function signature
Can declare a function with no args, then pass it some!
and access with arguments array within function
Example: factorial
Recursive calculation
Conditional statement
Calling from Change event
Use of document.getElementById
Use of this.value – gets value of current element
17. Factorial Form <html>
<head>
<script language="JavaScript">
function fac(n)
{ // do it recursively...
if (n < 2) {
return 1;
}
else {
return n * fac(n-1);
}
}
</script>
</head>
18. Factorial Form Contd. <body>
<form>
<p>
<input id="facArg" type="text"
onchange=" result = fac(this.value);
document.getElementById('facResult').value = result; " />
</p>
<p>
<input id="facResult" type="text" />
</p>
</form>
</body>
</html>
19. Form in action
20. Invoking JS from Hyperlinks JavaScript code can be the destination for a hyperlink
Use:
<a href=“javascript: myFunc(‘arg’)”>Click here to invoke myFunc(arg)</a>
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);
setAttribute(“class”, value);
In HTML
Function call on href
Alternative string quotes ‘’ to pass argument:
listStyle(‘noBullet’);
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