Events

berserkarithmeticInternet and Web Development

Dec 14, 2013 (3 years and 6 months ago)

143 views

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
generatedevents
„e.g., mouse-click
†
†
System
System
-
-
generated
generatedevents
„e.g., load event →triggered by web browser when
HTML document finishes loading
96
JavaScript events
97
HTML elements and associated events
98
HTML elements and associated events
2
99
How to catch Events?
†Code that executes in response to a
specific event
<
<
HTMLtag
HTMLtag
eventHandler
eventHandler
="
="
JavaScript
JavaScript
-
-
code
code
">
">
†Event handler naming convention „Event name with a prefix of "
on
on"
„E.g.,
onClick
onClick
<input type="button"onClick="alert(‘Youclicked the button!’)">
100
Using Events (Links)
†Primary event is the click event „For default operation, no event handler is required
†Overriding the default click event „Add
onClick
onClickevent handler that executes custom
code
„Event handler must return trueor false
„Can use built-in confirm()method to generate
Boolean value
101
Onclick() example
102
Onclick() example
3
103
Events and event handlers
onError
Error on loading an
image or a window
Images,
window
Error
onAbort
User aborts the
loading of an image
Images
Abort
onUnload
User exits the page
Document
body
Unload
onLoad
User loads the
page in a browser
Document
body
Load
HandlerOccurs whenApplies toEvent
104
Events and event
handlers(cont.)
onChange
User changes
the value of an
element
Text fields, text
areas, select lists
Change
onKeyPress
User presses or
holds down a
key
Documents, images,
links, text areas
KeyPress
onKeyUp
User releases a
key
Documents, images,
links, text areas
KeyUp
onKeyDown
User depresses
a key
Documents, images,
links, text areas
KeyDown
HandlerOccurs whenApplies toEvent
105
Events and event
handlers(cont.)
onClick
User clicks a
form element
or link
Buttons, radio
buttons, checkboxes,
submit buttons, reset
buttons, links
Click
onMouseUp
User releases
a mouse
button
Documents, buttons,
links
MouseUp
onMouseDo
wn
User
depresses a
mouse button
Documents, buttons,
links
MouseDown
HandlerOccurs whenApplies toEvent
106
Events and event
handlers(cont.)
onSelect
User selects form
element’s input
field
Text fields,
text areas
Select
onMouseOut
User moves
cursor out of an
image map or
link
Areas, links
MouseOut
onMouseOve
r
User moves
cursor over a link
Links
MouseOver
HandlerOccurs whenApplies toEvent
4
107
Events and event
handlers(cont.)
onDragDrop
User drops an
object onto the
browser window
Windows
DragDrop
onResize
User or script
resizes a window
Windows
Resize
onMove
User or script
moves a window
Windows
Move
HandlerOccurs whenApplies toEvent
108
Events and event
handlers(cont.)
onSubmit
User clicks a
Submit button
Forms
Submit
onReset
User clicks a Reset
button
Forms
Reset
onBlur
User moves focus
to some other
element
Windows and all
form elements
Blur
onFocus
User gives element
input focus
Windows and all
form elements
Focus
HandlerOccurs whenApplies toEvent
109
DOM
Document
Object
Model
†DOMhierarchy
110
Fields of window, I
†window
„The current window (not usually needed).
†self „Same as window.
†parent
„If in a frame, the immediately enclosing window.
†top
„If in a frame, the outermost enclosing window.
†frames
[ ]
„An array of frames (if any) within the current window. Frames are
themselves windows.
†length„The number of frames contained in this window.
5
111
Fields of window, II
†document„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.
†navigator„A 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"
†status„A read/write string displayed in the status area of the browser
window.
„Can be changed with a simple assignment statement.
112
Methods of window
†alert(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.
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).
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");
6
115
Fields of document, I
†You must prefix these fields with document.
†anchors[ ]
„An array of Anchorobjects (objects representing
<a name=...>tags)
<a name="sect14.6"><h2>The Anchor Object</h2></a>
†applets[ ]
„An array of Appletobjects
†The properties are the public fields defined in the applet
†The methods are the public methods of the applet
†Cautions:„You must supply values of the correct types for the fields and
method parameters
„Changes and method calls are done in a separate Thread
116
Fields of document, II
†forms[ ]„An array of
Form
elements
†If the document contains only one form, it is
forms[0]
†images[ ] „An array of Imageobjects
†To change the image, assign a new URL to the
srcproperty
†links[ ] „An array of Linkobjects
†A link has several properties, including href,
which holds the complete URL
117
Fields of document, III
†bgColor
„The background color of the document †May be changed at any time
†title
„A read-only string containing the title of the
document
†URL
„A read-only string containing the URL of the
document
118
Fields of the
form
formobject
†elements[ ]
„An array of form elements
var oForm = document.getElementById("form1");
var oForm = document.forms[0]; //get the first form
var oOtherForm = document.forms["formZ"]; //get the form whose
name is "formZ“
var oFirstField = oForm.elements[0]; //get the first form field
var 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"
7
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>
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>
121
Preloading images function 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' );
122
Debugging
†Mozilla/Netscape has much better debugging tools than IE
„Firefox†Select Tools =>Error Console
„Mozilla†Select 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 IE
„IE is the most popular browser
8
123
Warnings
†JavaScript is a big, complexlanguage
„We’ve only scratched the surface
„It’s easy to get started in JavaScript, but if you need to use
it heavily, plan to invest time in learning it well
„Write and test your programs a little bit at a time
†JavaScript is not totally platform independent!!!
„Expect different browsers to behave differently
„Write and test your programs a little bit at a time
†Browsers aren’t designed to report errors
„Don’t expect to get any helpful error messages
„Write and test your programs a little bit at a time
124
HTML names in JavaScript
†In HTML the windowis the global object
„The most important window property is document
†HTML formelements can be referred to by
document.forms[formNumber].elements[elementNumber]
†Every HTML formelement has a nameattribute
„The 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
125
JavaScript
Examples
126
Getting the date
<script type="text/javascript">
vard = new Date()
document.write(d.getDate() + "/")
document.write((d.getMonth() + 1) + "/")
document.write(d.getFullYear())
</script>
27/10/2003
9
127
Getting and formatting the
date
<script type="text/javascript">
vard=new Date()
varweekday=new Array ("Sunday",
"Monday","Tuesday","Wednesday",
"Thursday","Friday","Saturday")
varmonthname=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
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
129
Getting a random integer †The following code gets a random
integer between 1 and 10:
<script type="text/javascript">
varmax = 10;
number=Math.random()*max + 1;
document.write(Math.floor(number));
</script>
†5
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('Ohoh, something
happened!');">
</form>
10
131
Telling what happened
†In 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
132
Telling what happened
(Button)
†<input type="button"name="plainButton"value="PlainButton"
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');">
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 comment
varindexes = new Array(0, 1, 2, 3, 4, 5);
varnames = new Array("John","Mary","Adam","Zoe","Otis","Sarah");
varranks = new Array(4, 5, 1, 3, 6, 2);
varsortArray= indexes;
//document.writeln(document.URL+ "<br>");
varsortParamIndex= document.URL.lastIndexOf("sortby=");
134
Sorting a Table (ii)
if( sortParamIndex!= -1 ) {
varsortByStr=
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);
}
11
135
Sorting a Table (iii)function getNext(arr, lastIndex) {
// find the next best
varbestValue= arr[0];
varbestIndex= 0;
varisFirst= (lastIndex< 0);
varlastValue= arr[lastIndex];
for(i=1; i < arr.length; i++) {
varisLower= (arr[i] < bestValue);
varnotPrevious= (isFirst|| arr[i] > lastValue);
varisBestPrevious= (!isFirst&& (bestValue<= lastValue));
if( (isLower&& notPrevious) || isBestPrevious) {
bestValue= arr[i];
bestIndex= i;
}
}
return bestIndex;
}
varindex = getNext(sortArray, -1);
for(k=0; k < sortArray.length; k++ ) {
printRow(names[index], ranks[index], index);
index = getNext(sortArray, index);
}
// --></script></table>
136
Basic Rollover
<a href="http://www.w3c.org"
onMouseover="document.my_image.src=
‘sign_new.gif'"
onMouseout="document.my_image.src=
‘sign.gif'">
<imgsrc="sign.gif"width="30px"height="31px"
border="0"name="my_image"alt="MyImage">
</a>
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)
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)
12
139
Learn more here
Professional JavaScript for Web Developers
Professional JavaScript for Web Developers
Professional JavaScript for
Web Developers
„Publisher:Wrox (2005)
„ISBN-10:0764579088
„ISBN-13:978-0764579080
„Paperback:672 pages