Chapter 14 JavaScript and DHTML

Chapter 14 JavaScript and DHTML Presented by Thomas Powell Slides adopted from HTML & XHTML: The Complete Reference, 4th Edition ©2003 Thomas A. Powel...
Author: Stephany McCoy
36 downloads 2 Views 4MB Size
Chapter 14 JavaScript and DHTML Presented by Thomas Powell Slides adopted from HTML & XHTML: The Complete Reference, 4th Edition ©2003 Thomas A. Powell

Web Programming Toolbox Redux Client Side

Server Side

Helper Applications

CGI scripts and programs

Netscape Plug-ins ActiveX Controls

Server API Programs * ISAPI * NSAPI * Apache Modules

Java Applets

Java Servlets

Scripting Languages * JavaScript * VBScript

Server-side scripting * Active Server Pages (ASP) * ColdFusion * PHP

JavaScript Intro • Certainly the most popular Web client-side programming technology today • Difficult to characterize – Many names • JavaScript, Jscript, ECMAScript, DHTML, etc.

– Object Models Vary • Traditional DOM, IE4/5 Object Model, Nav 4, DOM Standard

– Not studied rigorously like most programming langs • Lots of “copy-paste” scripters • Generated code from editors like Dreamweaver

1

JavaScript’s Origins – Netscape 3 (late 1995) • Originally called LiveScript – Goal: Form validation and basic user handling

• Renamed JavaScript due to Java craze – Common misunderstanding about its relationship with Java – Not Java Lite, not as formal in OOP, etc.

– Microsoft introduces Jscript in IE 3 • Clone of JavaScript and few incompatibilities

– DHTML Wars of 4.x generation browsers • Both browsers introduce widely incompatible object models (e.g. Netscape 4 layers and IE’s document.all)

JavaScript Today – ECMA (European Computer Manufactuer’s Association) standardizes the core of JavaScript as ECMAScript • Handles the basic features like functions, variables, types, control structures, etc. • All major variants of JavaScript are ECMAScript compliant

– W3C creates a standard Document Object Model (DOM) • Modern browsers are compliant to one degree or another. Mozilla & Opera are very compliant, IE is fairly compliant • Should end DHTML wars

– Still JavaScript lacks respect, despite…

JavaScript Today Contd. – It is all around us • Flash’s ActionScript = ECMAScript + different objects • Many other languages based on it (LotusScript, etc.)

– It is used to build some very interesting things • Games, Outlook clones, message boards, etc.

– It is used to automate Dreamweaver! – It has fullfilled the promise given by Java Applets

• Likely outcome – JavaScript will be one of the four technologies you must know as a client-side developer • XHTML/HTML, XML, CSS, and JavaScript

2

First Example • JavaScript Hello World First JavaScript document.write("Hello World from JavaScript!");

Script and HTML Basics • element delimits HTML from JavaScript – Once within the element the “rules” change

• Two pass concept – First JavaScript interpreter fires and then HTML may be produced and rendered – Example

• Be careful with intermixing HTML and script code – Example of an error • Problem with browser error suppression • Need to know how to see the errors – Preference setting – JavaScript console

Script Inclusion Methods •

There are four standard ways to include script in an HTML document: 1. Within the element 2. As a linked file via the src attribute of the element 3. Within an HTML event handler attribute such as onclick 4. Via the pseudo-URL javascript: syntax referenced by a link Note: There are other approaches but they are non-standard

3

The Element • … – By default tends to interpret contents as JavaScript unless one of the following occurs: • Inclusion of language attribute – , etc.

• Inclusion of type attribute –

• The type attribute is W3C recommended, language more common and more useful • tag can also be used to set the script language document wide or even by a Web server. –

The Element Continued • You can use as many tags as you like in both the and and they are executed sequentially. •

Ready start alert("First Script Ran"); Running… alert("Second Script Ran"); Keep running alert("Third Script Ran"); Stop!

JavaScript in the •

function alertTest() { alert("Danger! Danger! JavaScript Ahead"); } Script in the Head alertTest();

4

Script Hiding and •

Script Hiding using HTML and JavaScript comments – – Avoids printing script onscreen in non-script aware browsers



Element – Useful to provide alternative rendering in browsers that have script off or don’t support script – Either your browser does not support JavaScript or it is currently disabled. – Next example shows a great way to keep non-JavaScript aware users out of your site

Exclusion Example •

Needs JavaScript JavaScript required
Read how to rectify this problem.

Event Handlers • HTML defines a set of event handler attributes related to JavaScript events such as onclick, onmouseover, etc. which you can bind JavaScript statements to. • There are both the core events defined by HTML 4 as well as common form and page events like onsubmit, onload, etc. •

Yahoo

5

Linked Scripts • Like linked style sheets you can store JavaScript code in a separate file and reference it – Use a .js file – Contains only JavaScript – Store these files like images in a common directory in your site (e.g. /scripts) – Linked scripts can be cached and “clean up” HTML documents – Linked scripts do have problems under some browsers

Linked Script Example •



Linked Script Example Contd. • In file danger.js you would have simply function alertTest( ) { alert("Danger! Danger!"); }

6

JavaScript Pseudo-URLs • You can use the JavaScript pseudo-URL to trigger a script statements • For example Click me • You can also type such a URL directly in the browser’s location box, for example javascript:alert(5+9) • Be aware that JavaScript pseudo-URLs do not degrade well in non-JavaScript aware browsers

Other JavaScript Inclusion Methods • There are a few other ways to include JavaScript in a Web page the most notable being the JavaScript entity supported by Netscape 4.x generation browsers • This method uses a standard HTML character entity in a macro style manner – &{script};

• You shouldn’t use this form of inclusion since it is no longer supported by even Netscape and is not cross browser in support

Learning JavaScript •

Simple syntax

– C like with some Perl and other characteristics – Three basic types (Numbers, Strings, Booleans) and some complex types (Arrays and Objects) • Loosely typed with lots of type conversion problems

– Interpreted language – The details are really well beyond the scope of this class though JavaScript: The Complete Reference or JavaScript I are both accessible once you actually understand HTML



Tip: Do not approach JavaScript unless you know HTML as its’ goal really is to manipulate HTML!



The next slides show a few issues about how tightly wound together HTML and JavaScript are

7

DHTML: What is it? •

Microsoft and Netscape extended the object model with a variety of new events



Dynamic HTML = CSS + DOM + Scripting + Extra “stuff”



DHTML really is just JavaScript



Some say DHTML is the use of JavaScript to move things around or perform other “Dynamic” effects



Let’s assume that DHTML refers to the concept of being able to manipulate arbitrary HTML in an aribtray ways

– Fits in with the marketing origin of the word, but still causes confusion

– Make tags, delete tags, move tags around, add style, delete style etc.

DOM Intro • The Document Object Model or DOM suggests that we think about a document as a collection of objects – In the case of Web documents tags = objects – Every tag makes an HTMLParagraph object, every tag a form object and so on

• Now that everything in the document has the ability to be scripted we see that naming is key – ID needs to be set and must be unique – NAME may also have to be used and interestingly does not have to be unique

Traditional DOM Example •

Meet and Greet What's your name?

8

DOM Example The Dynamic Paragraph: DOM Style The Dynamic Paragraph I am a dynamic paragraph. Watch me dance!

DOM Example 2 This is some text. New text:

DOM Thoughts • While the DOM is very powerful and shows the future the major browsers are not the same in their support for it and it is still difficult to make cross platform pages – People still are using libraries to handle differences (e.g. www.domapi.com)

• No matter how this turns out the ramifications of scripting are significant. – – – – –

Bugs Compatibility Testing Software development methodology Raises the “bar”

9

Using JavaScript • Ok maybe the DOM is not where you are today, but you should still be able to copy-paste or insert basic scripts into documents – Script library sites like dynamicdrive.com are useful – The book has some basic scripts including rollovers, form validation, pulldown navigation, and last modification date inclusion – Some editors like Dreamweaver can insert basic JavaScript easily – We look at the most common use of JavaScript here briefly

Form Validation Intro • Most common use of scripting on the Web is for form validation (checking the form fields for correctness before submission to a CGI program) • Basic stub –

• Then we need to write a function validate that returns true if all fields are ok and false if there are mistakes.

Form Validation • The key to form validation is naming your fields correctly and then either writing your own or using existing validation routine to check for common errors like: – – – – –

Blank fields Bad email formats Non-numeric data Bad dates Any other criteria you can think of

• Demo – By hand (see book page 467-470) – In Dreameaver

10