47
AdvisorEvents.com ADVISOR JumpStart: JavaScript Henry Newberry Teamwork Solutions, Inc. www.teamsol.com AJL201

Advisor Jumpstart: JavaScript

Embed Size (px)

Citation preview

Page 1: Advisor Jumpstart: JavaScript

AdvisorEvents.com

ADVISOR JumpStart: JavaScript

Henry NewberryTeamwork Solutions, Inc.www.teamsol.com

AJL201

Page 2: Advisor Jumpstart: JavaScript

AdvisorEvents.com

Who am I?

Director of Technical Services at Teamwork Solutions, Inc. (As of May, 2005)

Formerly President of Newbs Consulting, Inc. (2000-2005)

Cofounder of Synergistics, Inc. (1993-2000) Notes Pioneer at CBIS (1989-1993) Lotus Advisor Contributor and Speaker Lotus Advisor Editorial Advisory Panel Speaker at IBM Lotus events in 2002 & 2003

Page 3: Advisor Jumpstart: JavaScript

AdvisorEvents.com

This Session is JavaScript – NOT Java Two different languages for two very different

usages

JAVA jumpstart starts at 10:30 AM

J2EE – Java 2 Enterprise Edition - 2:00 PM

Page 4: Advisor Jumpstart: JavaScript

AdvisorEvents.com

"...hopefully JavaScript will just be a bad memory."

Iris AssociatesLotusphere EuropeFebruary 1997

"When users can do everything with JavaScript that they now do with LotusScript on the client-side, we will have reached our goal."

Iris AssociatesLotus Notes & Domino AdvisorMay 1999

Page 5: Advisor Jumpstart: JavaScript

AdvisorEvents.com

"JavaScript is the only viable client side development tool for browser

based applications."Henry NewberryA couple of weeks ago

Page 6: Advisor Jumpstart: JavaScript

AdvisorEvents.com

Session Overview

JavaScript overview (10-20 minutes) What, Who, Why, When Demo of what it can make the browser do

How to use JavaScript References, JavaScript sessions at DevCon Questions

Page 7: Advisor Jumpstart: JavaScript

AdvisorEvents.com

What Is JavaScript?

Nothing in common with Java! Netscape's Navigator 2.0 supported it in 1995

formerly LiveScript renamed JavaScript now properly called ECMAScript – but no one

really does that… In-line language - the code is included right in

with the HTML and data Sometimes referred to as "Dynamic HTML" Interpreted (not compiled) scripting language It makes the browser into a true web client

Page 8: Advisor Jumpstart: JavaScript

AdvisorEvents.com

Why use JavaScript? Advantages:

Many traditional client/server features are not available on the web due to browser limitations

JavaScript helps fill in most of the gaps Calculations, dynamic redirecting & submitting Field, form, and window event handlers Pop-up dialogs, new windows, framesets Dynamic graphics and mouse rollover events

Improved Performance Browser can perform certain functions instead of

having to submit and wait for the server

Page 9: Advisor Jumpstart: JavaScript

AdvisorEvents.com

Examples in this session will…

Demonstrate how it runs from the user's perspective

Show you what the code looks like Explain the code Answer any questions

Page 10: Advisor Jumpstart: JavaScript

AdvisorEvents.com

Demonstration of JavaScript Capabilities Validating user input Automatically recalculating values on the form Prompting the user for a reply Setting fields Dynamic keywords Launching a new window Changing graphics Displaying Layers Others

Cookies (storing values on the workstation) Collapse-able sections Getting and rendering XML

Page 11: Advisor Jumpstart: JavaScript

AdvisorEvents.com

Why not use JavaScript?Some Disadvantages... Does not work the same on all browsers Can be disabled by the user on their browser Source code can not be protected

Good if you're looking to borrow some code Bad for product development efforts

Page 12: Advisor Jumpstart: JavaScript

AdvisorEvents.com

Put JavaScript anywhere you put HTML Between SCRIPT tags (runs when page opens)

<SCRIPT LANGUAGE="JavaScript">alert("you opened this page");</SCRIPT>

Defining Event Handlers (runs when user clicks button)

<input type=Button value="Click Here" onClick="alert('you clicked this button.');">

Using javascript: protocol (runs when user clicks image)

<img src="/ImageFile.jpg" href="javascript:alert('you clicked this image.');">

Page 13: Advisor Jumpstart: JavaScript

AdvisorEvents.com

Document Object Model (DOM)

Page 14: Advisor Jumpstart: JavaScript

AdvisorEvents.com

Page 15: Advisor Jumpstart: JavaScript

AdvisorEvents.com

Jamie's "Mini DOM"

Example of referencing an object:document.forms[0].TextName.value

Page 16: Advisor Jumpstart: JavaScript

AdvisorEvents.com

Properties

Tell you something about the object Can be read or written (usually) Can lead to values or other objects in the DOM

document.forms is an array of objects of the class called “form”

document.title is text

Page 17: Advisor Jumpstart: JavaScript

AdvisorEvents.com

Methods

Are actions that you can tell the object to do Methods always have parenthesis:

form.submit()

Methods may take parameters (arguments) between parenthesis:

window.back( ) window.alert("this is a message in a popup box")

Page 18: Advisor Jumpstart: JavaScript

AdvisorEvents.com

Events

Events are Things that Happen to an Object JavaScript Code can be designed to execute

when the event occurs A JavaScript Method can direct which code

executes when an event occurs on an object

Page 19: Advisor Jumpstart: JavaScript

AdvisorEvents.com

The Main Events

onFocus: when the cursor is placed on an object (either with mouse or keyboard). Also applies to windows

onBlur: when the cursor was on the current object, but is then placed somewhere else (opposite of onFocus)

onChange: when a value changes onSubmit: when the form is submitted to the

server onClick: when a button is clicked onLoad: when a window is loaded onUnload: when a window is closed

Page 20: Advisor Jumpstart: JavaScript

AdvisorEvents.com

JavaScript Language Syntax

Based on C Case SeNsIvTiVe Ignores whitespaces (Indents, tabs, etc.) Semicolons optional (recommended for good

style) Uses // and /*...*/ for comments within the code

Variables Declare new ones with a "var" before the name of

the variable Refer to existing ones by not using "var" Type can be changed (effectively, a Variant data

type)

Page 21: Advisor Jumpstart: JavaScript

AdvisorEvents.com

JavaScript Data Types

Numbers Strings (can use single or double quotes) Boolean Values (True, False) Functions Objects Arrays Date/Time Special Object null or undefined REMEMBER: Type can be changed

Page 22: Advisor Jumpstart: JavaScript

AdvisorEvents.com

JavaScript Operators

Mathematical + - / * ++ (increment) -- (decrement)

String Manipulation charAt(index), split(char), substring(start, end)

Comparison: == (equals) != (not equal) > < <= >=

Logical: && (and) || (or) ! (not) Special: typeOf, this, new

Page 23: Advisor Jumpstart: JavaScript

AdvisorEvents.com

JavaScript Control Structures

If-thenif (condition) {

statementsIfTrue}

If-then-elseif (condition) {

statementsIfTrue} else {

statementsIfFalse}

Page 24: Advisor Jumpstart: JavaScript

AdvisorEvents.com

JavaScript Control Structure (con’t)

Conditional Assignmentresult = (condition) ? expression1 : expression2

For Loopsfor ([init expr]; [condition]; [update expr]){

statements}

For All Element Loopsfor (var in object) {

statements}

Page 25: Advisor Jumpstart: JavaScript

AdvisorEvents.com

JavaScript Control Structure (con’t)

Whilewhile (condition) {

statements}

Withwith (object) {

statements (.property or .methods}

Dodo {

statements} while (condition)

Page 26: Advisor Jumpstart: JavaScript

AdvisorEvents.com

JavaScript Control Structure (con’t)

Switchswitch (expression) {case valueone :

statements[break;] // optional but WATCH OUT.

case casevalue2 :statements[break;] // optional but WATCH OUT....

[default : // optionalstatements]

}

Page 27: Advisor Jumpstart: JavaScript

AdvisorEvents.com

More JavaScript Statements

break continue function return var escape unescape

Page 28: Advisor Jumpstart: JavaScript

AdvisorEvents.com

JavaScript Functions

Name of the function List of argument(s) in parenthesis Statements in curly braces

function functionName([arg1], [arg2]) {function functionName([arg1], [arg2]) { <code goes here><code goes here>

[return value][return value]}}

Page 29: Advisor Jumpstart: JavaScript

AdvisorEvents.com

Writing a JavaScript function

<INPUT type=BUTTON onClick="document.forms[0].Amount.value='5';document.forms[0].Amount.focus();">

is more useful and easier to maintain when expressed as...

<INPUT type=BUTTON onClick="setAmount('5')">

<SCRIPT language="JavaScript">function setAmount(v) {

document.forms[0].Amount.value=v;document.forms[0].Amount.focus();

}</SCRIPT>

Page 30: Advisor Jumpstart: JavaScript

AdvisorEvents.com

New Useful DOM Functions

getElementsByTagName(<tagname>) Returns an array of objects

getElementById(<id>) Returns a single object

Examples:

var myTable = document.getElementById(“myTable”)var cells = myTable.getElementsByTagName(“TD”)

Page 31: Advisor Jumpstart: JavaScript

AdvisorEvents.com

JavaScript Objects

JavaScript is object-based You can optionally create your own classes with:

Methods Properties

Process Created with the "new" statement Use the "this" reference to refer to the object

Use Classes instead of procedural functions

Page 32: Advisor Jumpstart: JavaScript

AdvisorEvents.com

Example of a JavaScript Object

<SCRIPT language="JavaScript">function PersonObj(f,m,l,phone,ssn) {

this.FirstName = f;this.MiddleName = m;this.LastName = l;this.phone = phone;this.ssn = ( ssn ) ? ssn : ‘-not supplied-’ ;

}

var theNewbs = new PersonObj(‘Henry’,’W’,’Newberry’,’513-245-1736’);var myBoss = new PersonObj(‘Scott’,’’,’Good’,’614-457-7100 x200’);var theRock = new PersonObj(‘Rockne’,’L’,’Oliver’,’770-967-3803’);

alert( “Hey It’s “ + theRock.Firstname );

</SCRIPT>

Page 33: Advisor Jumpstart: JavaScript

AdvisorEvents.com

JavaScript Arrays

JavaScript arrays are both indexed lists and tagged lists

Index elements 0 ... N Tag names can be used instead

Use the square brackets to refer to array elements

myArray[0] … myArray[n]myArray[‘rocky’]

The new method can initialize multiple elementsVar myArray = new (“Rocky”, “Henry”, “Scott”)

Page 34: Advisor Jumpstart: JavaScript

AdvisorEvents.com

Getting at the Data on a Page

Every Page has a window and document object The Forms object/array is a child of the document

object The Form object is the main point of entry to

your data May have multiple form instances, Domino generated pages have just one form,

document.forms[0] Submit action sends values back to the server

Page 35: Advisor Jumpstart: JavaScript

AdvisorEvents.com

Getting at the Data (con’t)

Data Fields are contained in a Form object: Text TextArea Selects RadioButtons CheckBoxes

When you use a Domino form these will have the same name as their Notes counterparts

Children of the Form object Getting field values (textboxes, listboxes, etc.)

Page 36: Advisor Jumpstart: JavaScript

AdvisorEvents.com

Debugging Your JavaScript

Using alert boxes IE JS Error dialog JavaScript Debuggers

The Microsoft script debugger: http://msdn.microsoft.com/scripting/

debugger/dbdown.htm The Netscape JavaScript debugger:

http://developer.netscape.com/software/tools/index.html?content=/software/jsdebug.html

only seems to work on scripts that are embedded in the HTML head doesn't like frames and child windows

Page 37: Advisor Jumpstart: JavaScript

AdvisorEvents.com

Client support for JavaScript

Client product JavaScript Level Netscape Navigator 2.x 1.0 MS Internet Explorer 3.x 1.0 Netscape Navigator 3.x 1.1 Netscape Navigator 4.0-4.05 1.2 MS Internet Explorer 4.x 1.2 Netscape Navigator 4.06-4.5 1.3 MS Internet Explorer 5.x 1.3 Lotus Notes 5.x 1.3 Netscape Navigator 5.x

1.4

Page 38: Advisor Jumpstart: JavaScript

AdvisorEvents.com

JavaScript vs. ECMAScript vs. JScript ECMAScript - Standard JavaScript. NetScape's

JavaScript "will always include features that are not part of the ECMA specification; JavaScript is compatible with ECMA, while providing additional features.“

Microsoft VBScript is based on Visual Basic Microsoft JScript is like JavaScript, but now IE

supports ECMAScript and just about all of JavaScript

Page 39: Advisor Jumpstart: JavaScript

AdvisorEvents.com

Some Advanced Concepts

Multiple forms JavaScript libraries, .js files

<SCRIPT Language="JavaScript" src="/filename.js">

The JavaScript calendar widget LiveConnect - make Java, JavaScript and Plug-Ins

interact with one another

Page 40: Advisor Jumpstart: JavaScript

AdvisorEvents.com

validateForm Function

function validateForm(f) {recalculateFields(); // call a functionif (f.CustomerName.value=="") {

alert("Please enter your name before submitting this order.");

f.CustomerName.focus(); // put the cursor in fieldreturn; // return to where this function was called

} else {f.submit(); // submit the form to the server

}}

Page 41: Advisor Jumpstart: JavaScript

AdvisorEvents.com

recalculateFields Functionfunction recalculateFields() {

var f = document.forms[0]; // so we don't have to repeatly use the// long expression

/* recalculate the unit prices */var i = f.Description.selectedIndex; // get the position of the selected Descriptionvar descriptionName = f.Description.options[i].text; // then, use the position to// get the namevar UnitPrice = getUnitPrice( descriptionName ); // finally, use the name to get// the pricef.UnitPrice.value = format(UnitPrice, 21, 2); // write the price to text // object's value property

/* recalculate the total price */var t = f.UnitPrice.value * f.Quantity.value; // compute the total pricef.Total.value = format(t, 21, 2); // set the Total field's value to// the formatted number t

}

Page 42: Advisor Jumpstart: JavaScript

AdvisorEvents.com

getUnitPrice Function

function getUnitPrice(itemType) {// get the price according to itemType

switch (itemType) {case "Lamp": // if it's a lamp...

return 25; // ...then its price is 25case "Chair": // etc...

return 100;case "Table":

return 400;default : // what to do if the itemType is

return 0; // not found, or it's blank}

}

Page 43: Advisor Jumpstart: JavaScript

AdvisorEvents.com

Things to watch out for!

Everything is case sensitive. Standardize! If you accidentally use the same variable name

for two objects, JavaScript doesn't tell you. Users may trigger JavaScript events before the

page is finished loading. Some statements don't run on all browsers. Test!

Page 44: Advisor Jumpstart: JavaScript

AdvisorEvents.com

Recommended Things to Have at Your Workstation Reference: You must get a good DOM chart

Danny Goodman's JS Object Road Map is included in the Session materials as an Adobe file JavaScriptObjectRoadMap.PDF. Prints nicely!

Learn more: The JavaScript Bible, Danny Goodman, IDG Books Worldwide, Fourth Edition 2000

Easy code writing: NetObjects Scriptbuilder Netscape Visual JavaScript

Testing: The Netscape JavaScript debugger

Page 45: Advisor Jumpstart: JavaScript

AdvisorEvents.com

Find Out More

1000's of JavaScript Examples you can re-usedir.yahoo.com/Computers_and_Internet/Programming_and_Development/Languages/

JavaScript/

Danny Goodman's site - Good FAQ’s etc.http://www.dannyg.com

Kurt Grigg’s sitewww.btinternet.com/~kurt.grigg/javascript/

More Sampleswww.urgentclick.com/javascript.htmlwww.hotscripts.com/JavaScript/index.html

Page 46: Advisor Jumpstart: JavaScript

AdvisorEvents.com

Other JS Sessions This Week Notes-to-Web series (Scott Good) Performance Engineering for Domino: How to

make your Apps Fly (Jamie MaGee) Websphere Portal: Advanced Portal Development

(Rob Novak) Customize IBM Lotus team Workplace (Rob

Novak) JavaScript and LotusScript Tricks for Domino

Applications (Henry Newberry)

Page 47: Advisor Jumpstart: JavaScript

AdvisorEvents.com

Questions?

Thank – YouPlease remember to fill out your evaluations