JavaScript 1 JavaScript 1 Introduction and DOM Dr Kevin McManus...
-
date post
15-Jan-2016 -
Category
Documents
-
view
229 -
download
0
Transcript of JavaScript 1 JavaScript 1 Introduction and DOM Dr Kevin McManus...
JavaScript 1
JavaScript 1
Introduction and DOM
Dr Kevin McManushttp://staffweb.cms.gre.ac.uk/~mk05/web/JavaScript/JavaScript1.html
© 2014 the University of Greenwich 2
JavaScript 1
What is JavaScript?• A scripting language developed in a collaboration
between Netscape and Sun Microsystems to provide client-side programming in web pages
• Introduced by Netscape in 1995• Executable JavaScript may be included into an HTML
page as either...• external
• a separate file containing JavaScript
• embedded• as the content of a <script> element
• inline• as the value of an HTML event attribute
© 2014 the University of Greenwich 3
JavaScript 1
What is JavaScript?• Not a full programming language like Java or C++
• core language has no graphics, no file handling, no networking
• Not a subset of Java - syntactically similar but:• loose data typing • object based not strictly object oriented
• although inheritance is possible
• Not simple - easy to get started but large and complex• client-side code is interpreted by the browser• it’s scope is restricted to the browser
• cannot carry a malicious payload
© 2014 the University of Greenwich 4
JavaScript 1
Versions of JavaScript • Originally introduced in Netscape Navigator 2.0 and Internet Explorer 3.0
• Very widely used on the web but for "serious applications" held back by:• incompatibilities between browsers • security issues• lack of a good IDE• perception of it as a "toy" language• these problems are now reducing
• Exists as:• core language • client-side version (with client side objects)• server-side version (with server side objects)
• Latest version is 1.5• Microsoft's version is officially called JScript• standard version of the core language is called ECMAScript
• European Computer Manufacturers Association
• JavaScript 1.3 is reported to be ECMA-262 compatible
© 2014 the University of Greenwich 5
JavaScript 1
Typical Uses• GUI enhancement
• rollovers images • pull-down menus• browser sniffing to adjust page layout
• Techniques to reduce the load on the server• validating input before sending to a server-side program• shopping carts
• Mini-applications• calculators, calendars
• Animation • Asynchronous applications
• AJAX
• Many of the above require DHTML• Dynamic HyperText Markup Language• combination of JavaScript & HTML & CSS & DOM
© 2014 the University of Greenwich 6
JavaScript 1
Discussion questions• Why might it be a good idea to use JavaScript to
offload work from the server to the client machine?
• What IPR (intellectual property rights) issues might be associated with use of JavaScript?
• Under what circumstance might browser compatibility issues not be a problem for a JavaScript developer?
• Can you think of at least two different strategies for dealing with browser compatibility problems.
© 2014 the University of Greenwich 7
JavaScript 1
First exampleembedding JavaScript in HTML
embed.html
var age = parseInt(prompt("Please enter your age", 29));
© 2014 the University of Greenwich 8
JavaScript 1
First exampleembedding JavaScript in HTML
embed.html
alert("You look younger than " + age)
© 2014 the University of Greenwich 9
JavaScript 1
First exampleembedding JavaScript in HTML
embed.html
document.write("<em>By the way I lie a lot!</em>")
© 2014 the University of Greenwich 10
JavaScript 1
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml11.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><title>JavaScript First Example</title></head><body><h1>JavaScript First Example</h1><p><script type="text/javascript"><!-- hide script from old non-Javascript browsersvar age = parseInt(prompt("Please enter your age", 29));if (isNaN(age)) { // if age is Not a Number (NaN) alert("You must enter a number");} else if (age < 23) { alert("You look more mature and sophisticated than " + age);} else { alert("You look younger than " + age); }document.write("<em>By the way I lie a lot!</em>");// end hiding from old browsers --></script></p><hr /><noscript><p>This page needs a JavaScript enabled browser</p></noscript></body></html>
<script> tag embedded in the HTML body, note the mandatory attribute
<!– HTML comment hides JavaScript from old browsers
JavaScript comment // hides HTML comment closing
<noscript> tag only supported by JavaScript browsers
© 2014 the University of Greenwich 11
JavaScript 1
Things to notice about embed.html var age• variables are not explicitly given data types
• JavaScript determines data type by context• JavaScript deals with three types:
• numbers• strings• booleans
= parseInt(prompt("Please enter your age", 29));• issues a prompt to the user for input• parses the input for an integer - parseInt()• assigns the result to the variable age. • The second parameter to prompt (29) is the default input and can
be omitted. • If the user doesn't input a number the variable age is set to the
special value NaN which can then be tested for.
© 2014 the University of Greenwich 12
JavaScript 1
Things to notice about embed.html if (isNaN(age)) { // if age is Not a Number (NaN)
alert("You must enter a number");
} else if (age < 23) {
alert("You look more mature and sophisticated than " + age);
} else {
alert("You look younger than " + age);
}
• JavaScript statements and expressions are similar to Java and C++• isNaN() returns true if the argument cannot be interpreted as a
number• alert() - issues an alert box with a message to the user
• see also confirm()• The ‘+’ character is overloaded
• used to concatenate strings or add numeric values• here it will concatenate because the first operand is a string
© 2014 the University of Greenwich 13
JavaScript 1
Quick Question
var age = prompt("Please enter your age", 29);
What do you think would happen if the code were just:
How do you find out what parseInt() and isNaN() do?
© 2014 the University of Greenwich 14
JavaScript 1
Things to notice about embed.html document.write("<em>By the way I lie a lot!</em>");
• document.write() outputs text into the current document in the browser window
• This will be interpreted by the browser as HTML• it can contain any valid HTML tags
• In this example the JavaScript is executed sequentially while the browser is laying out the HTML document • i.e. it happens after the
<h1>JavaScript First Example</h1><p>• and before the:
</p><hr />• this is one mode in which JavaScript code can be executed. • JavaScript is more commonly event-driven
• e.g. clicking a button, entering data in a text box or selecting a link
© 2014 the University of Greenwich 15
JavaScript 1
JavaScript Functions
} else { document.write("<h2>welcome to this mature page</h2>"); document.write("<p><img src='suit1.gif'/>"); document.write("<img src='suit2.gif'/>"); document.write("<img src='suit3.gif'/></p>"); }
JavaScript 1
<head><title>JavaScript functions</title><script type="text/javascript"><!-- hide script from old browsers
function Customise(userAge) { if (userAge < 10) { alert("Sorry you're too young for this page! - Bye"); history.back(); } else if (userAge < 20) { document.write("<h3>Welcome to this young page</h3>"); document.write("<p><img src='dolphin.gif'/></p>"); } else { document.write("<h3>welcome to this mature page</h3>"); document.write("<p><img src='suit1.gif'/>"); document.write("<img src='suit2.gif'/>"); document.write("<img src='suit3.gif'/></p>"); }}// end hiding from old browsers --></script></head>
Function defined in the document head but not executed until called
© 2014 the University of Greenwich 17
JavaScript 1
<body><h2>JavaScript - age sensitive page</h2><script type="text/javascript"><!-- hide script from old browsersvar age = parseInt(prompt("Please enter your age", 29));if (isNaN(age)) { alert("you should enter a numeric age");} else { Customise(age);}// end hiding from old browsers --></script><hr /></body></html >
functions.html continued
Function called as the browser renders the document
© 2014 the University of Greenwich 18
JavaScript 1
Things to notice about functions.html
• Syntax for declaring JavaScript functions• Functions may or may not take parameters
• call by value
• as with variables no data type is declared
• Functions can explicitly return to the calling code using the return statement (this one doesn’t).
• A value can be returned
• Functions should normally be declared in the <head> of the document
• they will be loaded into memory before they are called.
© 2014 the University of Greenwich 19
JavaScript 1
Things to notice about functions.html
• As with the previous example there is a normal
sequential flow of control through the <body> of the
document - the JavaScript code being executed as it
is encountered.
• history.back() returns the user to their previous
URL - i.e. one back in their “history” list • What sort of thing is history?
• What sort of thing is back()?
• How could the user not have a previous URL?
© 2014 the University of Greenwich 20
JavaScript 1
Ways of triggering JavaScript• Event handlers can be attached to HTML elements
• several dozen available• onFocus, onBlur, onChange, onSubmit, onClick, onMouseOver
<body onload="alert('Welcome - do stay a while')">
• This HTML event handler attribute is code to be executed when the onload event happens to the body element• the onload event occurs after the content has loaded
• i.e. when the corresponding closing </body> tag is encountered
• If more than one JavaScript statement is required they must be separated by a semicolon e.g.
<body onload="alert('Welcome - do stay a while'); alert('Some people find this page annoying...'); alert('why?')">
© 2014 the University of Greenwich 21
JavaScript 1
Ways of triggering JavaScript
• Triggered from an anchor tag using a javascript URL
<a href="javascript:void TodaysMenu()">Today's menu</a>
• When the link is taken the JavaScript code is executed
• if the code evaluates to a string then the string replaces the
current document in the browser window
• if, as here, a return of void is specified then the code specified is
just executed
javascript: pseudo-protocol specifier
code to be executed - in this case a function call
© 2014 the University of Greenwich 22
JavaScript 1
Switching to another document
The location property of the window object
window.location contains information about
the URL of the page currently on display. It can
be used by your JavaScript code to switch the
browser to another URL
window.location="http://home.netscape.com/";
© 2014 the University of Greenwich 23
JavaScript 1
Invoking JavaScript
© 2014 the University of Greenwich 24
JavaScript 1
Invoking JavaScript
Compare this with IE
© 2014 the University of Greenwich 25
JavaScript 1
Invoking JavaScript
Right click the link to open in a
new tab
Not the page we wanted
© 2014 the University of Greenwich 26
JavaScript 1
Invoking JavaScript
Prevents opening in a new tab
Can’t copy URL
© 2014 the University of Greenwich 27
JavaScript 1
<head> <title>Ways of invoking JavaScript</title> <script type="text/javascript"> <!-- Hide function TodaysMenu(){ // load menu, menu1.html and menu0.html alternate through the week var today = new Date(); var menuNumber = today.getDay() % 2; window.location = "menu" + menuNumber + ".html"; } // Stop Hiding --> </script> </head>
Invoking JavaScript
Modulus division
Called by onClick event and JavaScript URL
© 2014 the University of Greenwich 28
JavaScript 1
Invoking JavaScript<body onload="alert('Welcome - do stay a while')" onunload="alert('Au Revoir')"> <h1>Page to show the ways in which JavaScript can be invoked</h1> <p>JavaScript can be invoked a number of ways - here are three: </p><ul> <li>by sequential execution (see document.write() on this page)</li> <li>by event handlers (see onLoad, onMouseOver, onMouseOut and onClick on the page)</li> <li>by use of the JavaScript URL (see Link 2)</li> </ul> <p><a href="dummy.html" onclick="if (confirm('Really take the link?')) TodaysMenu(); return false;">Link</a>- illustrating event handlers </p><p> <a href="javascript: void TodaysMenu()">Today's menu</a> - illustrating use of the JavaScript URL</p><script type="text/javascript"> <!-- Hide document.write("<hr />"); // stop hiding --> </script> </body>
JavaScript URL
Sequential execution
Events
© 2014 the University of Greenwich 29
JavaScript 1
document.write()
• Can not be used to write content into the current document from within event handler invoked code
• Can only be used to write HTML into the current document as it is being loaded by the browser
• once this has finished (which is before the onLoad event occurs) then document.write() will overwrite the contents of the current window
• use the innerHTML property or an element to write into the current document after it has loaded
• we will look at that soon
• See what happens if document.write() is used in an event handler
© 2014 the University of Greenwich 30
JavaScript 1
Confirmationonclick="return confirm('Really take the link?')"
• confirm() is similar to alert() and prompt() in that it generates a message box.
• It returns a Boolean to indicate if the user selected “OK” or “cancel”
• If the onClick event for a link returns true the browser will follow the link
• otherwise it won’t.
© 2014 the University of Greenwich 31
JavaScript 1
JavaScript URL• Not so popular as event handlers.• Used to dynamically create document content or, as here, to
dynamically generate a link.
<a href="javascript:void TodaysMenu()">Today's menu</a>
• TodaysMenu() is defined as a function that switches the browser
to a URL depending on the day of the week.• clicking on the anchor will call the function.
• If you don't give a return type of void then the function can return
a string of text that will be displayed in the browser window - e.g.
"<html><body>mini document</body></html>"
© 2014 the University of Greenwich 32
JavaScript 1
Use of dates var today = new Date()• Creates a new date object (variable)
• by default set to today’s date and current time• stores a reference to it in the variable today
• Various methods can be used with Date objects:
today.getDay()• returns a number representing the day of the week• 0 for Sunday, 6 for Saturday
var menuNumber = today.getDay() % 2;window.location = "menu" + menuNumber + ".html";
• Here the day number is used to generate the name of an HTML document which is then loaded into the browser:
© 2014 the University of Greenwich 33
JavaScript 1
Quick Question
<a href="javascript:void TodaysMenu()">Today's menu</a>
<a href="" onclick="TodaysMenu(); return null">Today's menu</a>
Suppose the JavaScript URL feature didn't exist. How could the following line of code be changed to achieve the same result?
© 2014 the University of Greenwich 34
JavaScript 1
Debugging
• Mozilla browsers used to provide an exceedingly useful Error Console• which is one of several reasons why I always instructed students to use Firefox
• Firefox also provided powerful debugging with Firebug• Full breakpoint and symbolic debugging facilities for Mozilla was provided
by Venkman• now largely redundant
© 2014 the University of Greenwich 35
JavaScript 1
Debugging
• Things now move so fast it is difficult to keep pace
• Chrome started introducing highly sophisticated dev tools to lure us away from Firefox
• Firefox responded with new improved tools
This, or a similar tool in Chrome, is essential for effective web
development
© 2014 the University of Greenwich 36
JavaScript 1
Introduction to JavaScript objects
JavaScript objects can be classified into 3 types:
• object types built into the core language• Object, Array, String, Date, Math, RegExp
• client-side (or server-side) objects for interacting with
the browser and document (or server-side environment)• document, history, window, navigator
• programmer defined types of objects• rather different from defining classes in Java/C++
© 2014 the University of Greenwich 37
JavaScript 1
Introduction to JavaScript objects
• Objects have properties and methods associated with them
• referenced using the Java “dot” notation• window.location• history.back()
• New instances created using new• var today = new Date()
• Properties can be dynamically added to objects!• var today = new Date()• today.thingumebob = "Eeeek"• alert(today.thingumebob)
• To test if an object exists test the variable for null
© 2014 the University of Greenwich 38
JavaScript 1
Client-side objects
• Objects related to the browser window and HTML document are organised into a hierarchy
• NOT an inheritance hierarchy but an instance hierarchy of objects that reflect the structure of the HTML page.
• The top level object is the current window - all other client-side objects are directly or indirectly attached to this.
• The document object is directly attached to the current window• it forms the root for all other objects representing parts of the
HTML page
© 2014 the University of Greenwich 39
JavaScript 1
Client-side objects
current window
window related objects and properties
document
objects and properties representing the current HTML document
© 2014 the University of Greenwich 40
JavaScript 1
Document Object Modellevel 0
• What is described in these notes is known as the DOM level 0• invented by Netscape
• Supported (mostly) by the version 3 browsers onwards
• High degree of compatibility between browsers• Extended considerably by DOM level 1, 2 and
level 3• provide fine grain access to the document markup
and content• standardised by the W3C
© 2014 the University of Greenwich 41
JavaScript 1
DOMwindow
.location.document.history .navigator
.anchors[ ].links[ ]
button
checkboxtext
textarea
hiddenselect
.options[ ]
.objects[ ].images[ ]
radio
form elements indicate the different types of objects in the elements[] array rather than separate objects.elements[ ]
.forms[ ]
© 2014 the University of Greenwich 42
JavaScript 1
Object hierarchy
• The document object represents the current HTML document.
• All the aspects of the document that you can access in JavaScript using DOM level 0 are represented as properties of the document object
• DOM level 1 and level 2 allow you to get access to far more element of the current page.
• images[], forms[], anchors[], etc. are arrays• So document.forms[1] represents the second form
defined in the current document.
© 2014 the University of Greenwich 43
JavaScript 1
Object hierarchy• elements[] is an array representing all the components of a
form (buttons, textareas, radio buttons etc)• document.forms[0].elements[3] would represent the fourth
element defined in the first form of the current document.
<form action="dummy"><h3>There are:</h3><p><input type="text" name="txtDays" size="5" /> Days<br /><input type="text" name="txtHours" size="5" /> Hours<br /><input type="text" name="txtMins" size="5" /> Minutes<br /><input type="text" name="txtSecs" size="5" /> Seconds</p>
• Although object names need to be qualified you don’t need to include window at the beginning of all objects (or properties or methods) belonging to the current window• window.location is equivalent to location
© 2014 the University of Greenwich 44
JavaScript 1
Accessing form elements xmasCountdown.html
Note this button
JavaScript 1
<head><title>Xmas Countdown</title> <script type="text/javascript"> <!-- hide script from old browsers var xmas = new Date("December 25, 2014 00:00:00") ;function CalcRemaining() { var now = new Date(); var difference = parseInt((xmas.getTime() – now.getTime()) / 1000); var secs = difference % 60; difference = parseInt(difference / 60); var minutes = difference % 60; difference = parseInt(difference / 60); var hours = difference % 24; difference = parseInt(difference / 24); var days = difference; document.forms[0].elements[0].value = days; document.forms[0].elements[1].value = hours; document.forms[0].elements[2].value = minutes; document.forms[0].elements[3].value = secs;} // end hiding from old browsers --> </script> </head>
calculate the days, hours, mins, secs remaining until Xmas
© 2014 the University of Greenwich 46
JavaScript 1
<body onload="CalcRemaining()"><h2>Xmas Countdown!</h2><form action="dummy"><h3>There are:</h3><p><input type="text" name="txtDays" size="5" /> Days<br /><input type="text" name="txtHours" size="5" /> Hours<br /><input type="text" name="txtMins" size="5" /> Minutes<br /><input type="text" name="txtSecs" size="5" /> Seconds</p><p>remaining until Xmas 2007.</p><p><input type="button" value="Re-display clock" onclick="CalcRemaining()"/></p></form></body></html>
xmasCountdown.html
© 2014 the University of Greenwich 47
JavaScript 1
xmasImproved.html
• The rather cumbersome syntax
document.forms[0].elements[0].value = days
• Can be simplified by passing the form into the function
<body onload="CalcRemaining(document.forms[0])">
<input type="button" value="Re-display clock" onclick="CalcRemaining(this.form)">
• this refers to the current object (the button)• this.form refers to the form that this belongs to.• Address the form inputs by name
function CalcRemaining(theForm) { ... theForm.txtDays.value = days;
© 2014 the University of Greenwich 48
JavaScript 1
Accessing parts of the document• The IE document.all collection allows dynamic
access to all elements of the document• a collection of all HTML elements in the document indexed by:
• element number document.all(2) is the 3rd HTML element on the page
• element id document.all("MyPara") is the HTML element with matching id or name attribute value
<p id="MyPara">blah blah blah</p> or simply using dot notation
document.all.MyPara
• NOT available on other browsers• so you MUST NOT use it
• included here to explain legacy code
© 2014 the University of Greenwich 49
JavaScript 1
Accessing parts of the document
• Netscape introduced layers to implement DHTML• alternative to document.all but now largely obsolete
• A simple technique that works across all modern browsers is the getElementById() method• document.getElementById('foo') matches the HTML
element which has an id attribute value of 'foo'• id values must be unique within a document
• The DOM does not exist until after the page has loaded• obviously!• so DHTML techniques using the DOM are best restricted to
use in event handlers
© 2014 the University of Greenwich 50
JavaScript 1
xmasDHTML.html
• HTML elements have an innerHTML property• allows control over the element contentdocument.getElementById('pageTitle').innerHTML =
"Shopping days until Xmas"
• innerHTML may contain HTML markup• dynamic alteration of the DOM
• HTML element attributes are exposeddocument.getElementById('update').title =
"click here to update the countdown"
• the element style attribute allows control of the element presentation
document.getElementById('clock').style.fontSize = "1.5em"
Beware
IE replaces all innerHTML whitespace with a single space character.
This will cause problems with line breaks (\n) in <pre> and <textarea> elements.
© 2014 51
JavaScript 1
xmasDHTML.html
© 2014 the University of Greenwich 52
JavaScript 1
Summary• JavaScript provides client-side programming for HTML
web pages invoked as:• embedded code• event driven• JavaScript URL
• Document Object Model (DOM) provides a means of addressing HTML components of web pages• after the page has loaded
• addressed as an array
• addressed by name
• preferably addressed by ID
• Enables dynamic control of the appearance and the content of web pages - DHTML
© 2014 the University of Greenwich 53
JavaScript 1
Any Questions?