it engineering i.03.javascript.ver.2.6 - amirkabir...

45
1 95 Events Event: A specific circumstance that is monitored by JavaScript or, A trigger that fires specific JavaScript code in response to a given situation e.g., an action that a user takes User User - - generated generated events e.g., mouse-click System System - - generated generated events e.g., load event triggered by web browser when HTML document finishes loading

Upload: ngohuong

Post on 16-Apr-2018

218 views

Category:

Documents


5 download

TRANSCRIPT

1

95

EventsEvent:

A specific circumstance that is monitored by JavaScript or,A trigger that fires specific JavaScript code in response to a given situation

e.g., an action that a user takes

UserUser--generatedgenerated eventse.g., mouse-click

SystemSystem--generatedgenerated eventse.g., load event → triggered by web browser when HTML document finishes loading

2

96

JavaScript events

3

97

HTML elements and associated events

4

98

HTML elements and associated events

5

99

How to catch Events?

Code that executes in response to a specific event<<HTMLtagHTMLtag eventHandlereventHandler="="JavaScriptJavaScript--codecode">">

Event handler naming conventionEvent name with a prefix of "onon"

E.g., onClickonClick

<input type="button" onClick="alert(‘You clicked the button!’)">

6

100

Using Events (Links)Primary event is the click event

For default operation, no event handler is required

Overriding the default click eventAdd onClickonClick event handler that executes custom code

Event handler must return true or false

Can use built-in confirm() method to generate Boolean value

7

101

Onclick() example

8

102

Onclick() example

9

103

Events and event handlers

onErrorError on loading an image or a window

Images, window

Error

onAbortUser aborts the loading of an image

ImagesAbort

onUnloadUser exits the pageDocument body

Unload

onLoadUser loads the page in a browser

Document body

Load

HandlerOccurs whenApplies toEvent

10

104

Events and event handlers(cont.)

onChangeUser changes the value of an element

Text fields, text areas, select lists

Change

onKeyPressUser presses or holds down a key

Documents, images, links, text areas

KeyPress

onKeyUpUser releases a key

Documents, images, links, text areas

KeyUp

onKeyDownUser depresses a key

Documents, images, links, text areas

KeyDown

HandlerOccurs whenApplies toEvent

11

105

Events and event handlers(cont.)

onClickUser clicks a form element or link

Buttons, radio buttons, checkboxes, submit buttons, reset buttons, links

Click

onMouseUpUser releases a mouse button

Documents, buttons, links

MouseUp

onMouseDown

User depresses a mouse button

Documents, buttons, links

MouseDown

HandlerOccurs whenApplies toEvent

12

106

Events and event handlers(cont.)

onSelectUser selects form element’s input field

Text fields, text areas

Select

onMouseOutUser moves cursor out of an image map or link

Areas, linksMouseOut

onMouseOver

User moves cursor over a link

LinksMouseOver

HandlerOccurs whenApplies toEvent

13

107

Events and event handlers(cont.)

onDragDropUser drops an object onto the browser window

WindowsDragDrop

onResizeUser or script resizes a window

WindowsResize

onMoveUser or script moves a window

WindowsMove

HandlerOccurs whenApplies toEvent

14

108

Events and event handlers(cont.)

onSubmitUser clicks a Submit button

FormsSubmit

onResetUser clicks a Reset button

FormsReset

onBlurUser moves focus to some other element

Windows and all form elements

Blur

onFocusUser gives element input focus

Windows and all form elements

Focus

HandlerOccurs whenApplies toEvent

15

109

DOM

Document

Object

ModelDOM hierarchy

16

110

Fields of window, Iwindow

The current window (not usually needed).

selfSame as window.

parentIf in a frame, the immediately enclosing window.

topIf in a frame, the outermost enclosing window.

frames[ ]

An array of frames (if any) within the current window. Frames are themselves windows.

lengthThe number of frames contained in this window.

17

111

Fields of window, IIdocument

The HTML document being displayed in this window. location

The URL of the document being displayed in this window. If you set this property to a new URL, that URL will be loaded into this window. Calling location.reload() will refresh the window.

navigatorA reference to the Navigator (browser) object. Some properties of Navigator are:

appName -- the name of the browser, such as "Netscape"platform -- the computer running the browser, such as "Win32"

statusA read/write string displayed in the status area of the browser window. Can be changed with a simple assignment statement.

18

112

Methods of windowalert(string)

Displays an alert dialog box containing the string and an OK button.

confirm(string)Displays a confirmation box containing the string along with Cancel and OK buttons. Returns true if OK is pressed, false if Cancel is pressed.

prompt(string)Displays a confirmation box containing the string, a text field, and Cancel and OK buttons. Returns the string entered by the user if OK is pressed, null if Cancel is pressed.

19

113

Methods of window

open(URL)Opens a new window containing the document specified by the URL.

close()Closes the given window (which should be a top-level window, not a frame).

20

114

Examples of window<a href="help.html"

onmouseover="status='Get Help Now!';">Help</a>

window.open("someDoc.html", "newWind", "menubar,status,resizable");

window.open("someDoc.html", "newWind","menubar=1,status=1,resizable=1");

21

115

Fields of document, IYou must prefix these fields with document.anchors[ ]

An array of Anchor objects (objects representing<a name=...> tags)

<a name="sect14.6"><h2>The Anchor Object</h2></a>

applets[ ] An array of Applet objects

The properties are the public fields defined in the appletThe methods are the public methods of the appletCautions:

You must supply values of the correct types for the fields and method parametersChanges and method calls are done in a separate Thread

22

116

Fields of document, IIforms[ ]

An array of Form elementsIf the document contains only one form, it is forms[0]

images[ ] An array of Image objects

To change the image, assign a new URL to the src property

links[ ] An array of Link objects

A link has several properties, including href, which holds the complete URL

23

117

Fields of document, IIIbgColor

The background color of the documentMay be changed at any time

titleA read-only string containing the title of the document

URLA read-only string containing the URL of the document

24

118

Fields of the formform objectelements[ ]

An array of form elementsvar oForm = document.getElementById("form1");var oForm = document.forms[0]; //get the first formvar oOtherForm = document.forms["formZ"]; //get the form whose

name is "formZ“

var oFirstField = oForm.elements[0]; //get the first form fieldvar oTextbox1 = oForm.elements["textbox1"];//get the field with

the name "textbox1"oTextbox1 = oForm.textbox1; //get the field with the name

"textbox1"If the name has a space in it, use bracket notation instead:var oTextbox1 = oForm["text box 1"]; //get the field with the name "text box 1"

25

119

document fields<hr><font size="1">Document: <i><script> document.write(document.title);</script></i><br>URL:<i><script> document.write(document.URL);</script></i><br>Last Update:<i><script> document.write(document.lastModified);</script></i></font>

26

120

document.referer<script>

// If linked from somewhere offsite, go to home page first

if (document.referrer == "" || document.referrer.indexOf("mysite.com") == -1)

window.location = "http://www.mysite.com/";

</script>

27

121

Preloading imagesfunction simplePreload() {

var args = simplePreload.arguments;document.imageArray = new Array( args.length );for(var i = 0; i < args.length; i++ ) {document.imageArray[i] = new Image;document.imageArray[i].src = args[i];}

}...simplePreload( 'pictures/cat2.jpg', 'pictures/dog10.jpg' );

28

122

DebuggingMozilla/Netscape has much better debugging tools than IE

FirefoxSelect Tools =>Error Console

MozillaSelect Tools => Web Development => JavaScript console

Netscape 6:Select Tasks => Tools => JavaScript console

Any Mozilla or Netscape:Type javascript: in the location bar and press Enter

Internet Explorer:Go to the Preferences... dialog and look for something like Web content => Show scripting error alerts

After debugging, test your program in IEIE is the most popular browser

29

123

WarningsJavaScript is a big, complex language

We’ve only scratched the surfaceIt’s easy to get started in JavaScript, but if you need to use it heavily, plan to invest time in learning it wellWrite and test your programs a little bit at a time

JavaScript is not totally platform independent!!!Expect different browsers to behave differentlyWrite and test your programs a little bit at a time

Browsers aren’t designed to report errorsDon’t expect to get any helpful error messagesWrite and test your programs a little bit at a time

30

124

HTML names in JavaScriptIn HTML the window is the global object

The most important window property is document

HTML form elements can be referred to by document.forms[formNumber].elements[elementNumber]

Every HTML form element has a name attributeThe name can be used in place of the array reference

<form name="myForm"><input type="button" name="myButton" ...>

Then instead of document.forms[0].elements[0]you can say document.myForm.myButton

31

125

JavaScript

Examples

32

126

Getting the date<script type="text/javascript">

var d = new Date()document.write(d.getDate() + "/")document.write((d.getMonth() + 1) + "/")document.write(d.getFullYear())

</script>

27/10/2003

33

127

Getting and formatting the date

<script type="text/javascript">var d=new Date()var weekday=new Array ("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday")var monthname=new Array("Jan", "Feb", "Mar","Apr",May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")

document.write(weekday[d.getDay()] + ", ");document.write(monthname[d.getMonth()] + " " +

d.getDate() + ", ");document.write(d.getFullYear());

</script>Monday, Oct 27, 2003

34

128

Getting a random number

The following code gets a random floating-point number between 0 and 1:

<script type="text/javascript">document.write(Math.random())

</script>

0.728762788388911

35

129

Getting a random integer

The following code gets a random integer between 1 and 10:

<script type="text/javascript">var max = 10;number=Math.random()*max + 1;document.write(Math.floor(number));

</script>

5

36

130

Displaying an alert box

The following code displays an alert box when a button is clicked:

<form> // Buttons can only occur within form

<input type="button" name="Submit"value="Alert!" onclick="alert('Oh oh, something happened!');">

</form>

37

131

Telling what happenedIn the <head> of the HTML page define:

<script><!--function tell(a, b) {

document.forms[0].result.value+="\n"+a+": " + b;}//-->

</script>For each form element, I have a handler for every (plausible) event

38

132

Telling what happened (Button)

<input type="button" name="plainButton" value="Plain Button"onMouseDown="tell(this.name, 'onmousedown');"onMouseUp="tell(this.name, 'onmouseup');"onClick="tell(this.name,'onclick');"onDblClick="tell(this.name,'ondblclick');"onFocus="tell(this.name, 'onfocus');"onBlur="tell(this.name, 'onblur');"onMouseOver="tell(this.name, 'onmouseover');"onMouseOut="tell(this.name, 'onmouseout');"onChange="tell(this.name, 'onchange');"onKeyPress="tell(this.name, 'onkeypress');"onKeyDown="tell(this.name, 'onkeydown');"onKeyUp="tell(this.name, 'onkeyup');"onSelect="tell(this.name, 'onselect');"onReset="tell(this.name, 'onreset');">

39

133

Sorting a Table (i)<title>Web Page</title><table border="1" name="table0"><br><tr><th><a href="?sortby=names">Name</a><th><a href="?sortby=ranks">Rank</a><th><a href="?sortby=indexes">Index</a>

<script language="JavaScript"><!-- html commentvar indexes = new Array(0, 1, 2, 3, 4, 5);var names = new Array("John", "Mary", "Adam", "Zoe", "Otis", "Sarah");var ranks = new Array(4, 5, 1, 3, 6, 2);

var sortArray = indexes;

//document.writeln(document.URL + "<br>");var sortParamIndex = document.URL.lastIndexOf("sortby=");

40

134

Sorting a Table (ii)if( sortParamIndex != -1 ) {var sortByStr =

document.URL.slice(sortParamIndex+7);// document.writeln(sortByStr + "<br>");if( sortByStr === "names" ) sortArray = names;if( sortByStr === "ranks" ) sortArray = ranks;if( sortByStr === "indexes" ) sortArray = indexes;

}function printRow(name, rank, index) {

document.writeln("<TR><TD>" + name + "<TD>" + rank + "<TD>" + index);

}

41

135

Sorting a Table (iii)function getNext(arr, lastIndex) {

// find the next bestvar bestValue = arr[0];var bestIndex = 0;var isFirst = (lastIndex < 0);var lastValue = arr[lastIndex];for(i=1; i < arr.length; i++) {

var isLower = (arr[i] < bestValue);var notPrevious = (isFirst || arr[i] > lastValue);var isBestPrevious = (!isFirst && (bestValue <= lastValue));if( (isLower && notPrevious) || isBestPrevious ) {

bestValue = arr[i];bestIndex = i;

}}return bestIndex;

}var index = getNext(sortArray, -1);for(k=0; k < sortArray.length; k++ ) {

printRow(names[index], ranks[index], index);index = getNext(sortArray, index);

}// --></script></table>

42

136

Basic Rollover<a href="http://www.w3c.org"

onMouseover="document.my_image.src=

‘sign_new.gif'"onMouseout="document.my_image.src=

‘sign.gif'">

<img src="sign.gif" width="30px" height="31px"border="0" name="my_image" alt="My Image">

</a>

43

137

It’s fun ☺javascript:R=0; x1=.1; y1=.05; x2=.25; y2=.24; x3=1.6; y3=.24; x4=300; y4=200; x5=300; y5=200; DI=document.images; DIL=DI.length; function A(){for(i=0; i<DIL; i++){DIS=DI[ i ].style; DIS.position='absolute'; DIS.left=Math.sin(R*x1+i*x2+x3)*x4+x5; DIS.top=Math.cos(R*y1+i*y2+y3)*y4+y5}R++}setInterval('A()',5); void(0)

44

138

Try it!javascript:R=0; x1=.1; y1=.05; x2=.25; y2=.24; x3=1.6; y3=.24; x4=300; y4=200; x5=300; y5=200; DI=document.images; DIL=DI.length; function A(){

for(i=0; i<DIL; i++){DIS=DI[ i ].style; DIS.position='absolute';DIS.left=Math.sin(R*x1+i*x2+x3)*x4+x5;DIS.top=Math.cos(R*y1+i*y2+y3)*y4+y5

}R++

}setInterval('A()',5); void(0)

45

139

Learn more hereProfessional JavaScript for Web DevelopersProfessional JavaScript for Web Developers

Professional JavaScript for Web Developers

Publisher: Wrox (2005)

ISBN-10: 0764579088

ISBN-13: 978-0764579080

Paperback: 672 pages