Transcript Slide 1

Event Handlers
Events are asynchronous.
When an event occurs, JavaScript can execute code
in response to the user’s action. This response to the
user-initiated event is called event handling.
Event handlers are not enclosed between
<script></script> tags. They are attributes of HTML
tags. The string that is assigned to the event handlers
is the command that will be executed when the event
is triggered by the user.
onClick event – E1
<html>
<head><title>Wake up call</title>
<script language="javascript">
function wakeupCall(){
setTimeout('alert("Time to get up!")',5000);
}
</script>
</head>
<body bgcolor="lightblue">
<form>
<input type="button"
value="Wake me"
onClick="wakeupCall()">
</form>
</body>
</html>
<html>
onUnload, onClick events – E2
<head><title>An event</title></head>
<body bgcolor="magenta" onUnload="alert('So long,
stranger!')";>
<center>
<form>
<input type="button"
value="Click here to be alerted"
onClick='alert("Watch out! An asteroid is approaching
earth!")'>
</form>
</center>
</body>
</html>
<html>
onFocus, onClick events– E3
<head><title>Simulation Methods</title></head>
<body bgcolor="yellow">
<form name="myform"
action="http://localhost/cgi-bin/doit.pl" method="post">
Enter your name:<br>
<input type="text"
name="namefield"
size="30"
value="Name: "
onFocus="this.select()">
<p>
Enter your address:<br>
<input type="text"
name="addressfield"
size="30"
value="Address: "
onFocus="this.select()">
<p>
</form>
<a href="#" onClick="javascript: document.myform.submit();">
Click here to submit your form</a>
<p>
<a href="#" onClick="javascript:document.myform.reset();">
Click here to reset your form</a>
</body>
</html>
<html>
onSubmit event - Return Values – E4
<head><title>An HTML Form and the onSubmit Event Handler</title>
<script language="JavaScript">
function checkForm(yourinfo){
if(yourinfo.namestring.value == "" || yourinfo.namestring.value == null){
alert("Please type in your name");
return(false);
}
else{return(true);}
}
</script>
</head>
<body>
<b>
<form name="info" action="/cgi-bin/bookstuff/form1.cgi" method="post"
onSubmit="return checkForm(document.info)"><p>
<font size="+1"><p>
Type your name here:
<input type="text" name="namestring" size="50">
<p>
<input type="submit" value="Submit">
<input type="reset" value="Clear">
</form>
</body>
</html>
<html>
onLoad, onUnload events – E5
<head><title>Mouse Events</title>
<script language="JavaScript">
var sec=0;
function now(){
var newdate= new Date();
var hour=newdate.getHours();
var minutes=newdate.getMinutes();
var seconds=newdate.getSeconds();
var timestr=hour+":"+minutes+":"+seconds;
window.setInterval("trackTime()", 1000);
alert("Your document has finished loading\n"+
"The time: "+timestr);
}
function trackTime(){
sec++;
}
function howLong(){
alert("You have been browsing here for "+ sec+" seconds");
}
</script>
</head>
<body background=“fall.jpg" onLoad="now();" onUnLoad="howLong();">
<font face="arial,helvitica" size=5>
When you leave or reload this page, <br>an alert dialog box will appear.
</body>
</html>
onFocus, onBlur events – E6
<!--html main document (example-12.6.html-->
<html>
<head><title>Frame Me!</title></head>
<frameset cols="25%,75%">
<frame src="leftfocus.html" name="left">
<frame src="rightfocus.html" name="right" >
</frameset>
</html>
<!--file leftfocus.html -->
<html>
<head><title>Left Frame</title>
<script language="JavaScript">
function focus_on_me(){
document.bgColor="pink"; // Current doc is the left frame
window.status="focus leftframe";
}
function defocus_me(){
parent.left.document.bgColor="yellow"; // Another way to reference
window.status="focus rightframe"; // See the status bar
}
</script>
</head>
<body onFocus="focus_on_me()" onBlur="defocus_me()" bgColor="lightgreen">
<image src="spring.jpg">
</body>
</html>
<!--file rightfocus.html -->
<html>
<head><title>Right Frame</title></head>
<body bgColor="lightblue">
<font face="arial" size=4> right frame<br>
</body>
</html>
focus(), blur() methods – E7
<html>
<head><title>The focus and blur methods</title>
<script language="JavaScript">
function newWindow(){
winObj=window.open("summertime.jpg",
"summer","width=650,height=200,resizable=yes,scrollbars=yes,location=yes");
winObj.moveTo(0,0); // Move to lefthand corner of screen
winObj.focus(); // New window gets the focus
//winObj.blur();
}
function closeWindow(){
winObj.close(); // Close the new window
}
</script>
</head>
<body bgColor="lightgreen">
<h2>Summer Scene from the Old Country</h2>
<form>
<input type=button
value="Open Window"
onClick="javascript:newWindow();">
<input type=button
value="Close Window"
onClick="javascript:closeWindow();">
</form>
</body>
</html>
onDblClick, onMouseOver, onMouseOut Events
– E8
<html>
<head><title>Mouse Events</title>
<script language="JavaScript">
var counter=0;
function alertme(){
alert("I'm outta hea!");
window.close();
}
function track_Moves(){
counter++;
if(counter==1){alert(counter + " mouse move so far!");}
else{alert(counter + " mouse moves so far!");}
}
</script>
</head>
<body bgColor="CCFF00" onDblClick="alertme()";>
<p><font face="arial" size=3>Double click anywhere on this page to get out!
<p>When the mouse moves over the link, an event is triggered.
<a href="#" onMouseOver="alert('Event: onMouseOver');">onMouseOver</a>
<p>When the moves away from a link, an event is triggered.
<a href="#" onMouseOut="alert('Event: onMouseOut');">onMouseOut</a>
<p>When the mouse moves in or out of the button, a function<br> is called that keeps track of how many times the mouse touched the button.
<form>
<input type="button"
value="onMouseMove"
onMouseMove="track_Moves();">
</form>
</body>
</html>
onMouseOver, onMouseOut events – E9
<html>
<head><title>Mouse Events</title></head>
<body bgColor="orange">
<a href="#“ onMouseOver="document.mouse.src='mouse.jpg'">
onMouseOver </a><p>
<a href="#" onMouseOut="document.mouse.src='mouse2.gif'">
onMouseOut</a><p>
<img src="mouse2.bmp" width=300 height=150 name="mouse">
</body>
</html>
SlideShow – E10
<html><head><title>The Four Seasons</title>
<script language="JavaScript">
var season = new Array();
var indx = 0;
var timeDelay=2000;
if(document.images){
season[0]=new Image();
season[0].src="winter.jpg";
season[1]=new Image();
season[1].src="summer.jpg";
season[2]=new Image();
season[2].src="fall.jpg";
season[3]=new Image();
season[3].src="spring.jpg";
}
function changeSeason(){
var size= season.length - 1;
if( indx < size ) {indx++;}
else {indx = 0;}
document.times.src= season[indx].src;
timeout=setTimeout('changeSeason()', timeDelay);
}
function stopShow(){clearTimeout(timeout);}
</script>
</head>
<body bgcolor="cornflowerblue"><center><font face="arial">
<h2>The 4 Seasons</h2><b>
To see slide show, put your mouse on the image.<br>Move your mouse away from the image, to stop it.
<a href="javascript:void(null);“ onMouseOver="return changeSeason();“ onMouseOut="return stopShow()">
<img name="times" src="winter.jpg" align="left“ border=8 hspace="10" width="700" height="200"></a><br>
</body>
</html>
onClick event on a link – E11
<html>
<head><title>De-activate the hotlink</title></head>
<body>
<center>
<a href="#" onClick='alert("This hotlink is out of
service!"); return false;’>Click here</a>
</center>
</body>
</html>
onClick on buttons with “this” – E12
<html>
<head><title>The this keyword</title>
<script language="JavaScript">
function display_formval(myform){
alert("Form's text value: " + myform.namestring.value );
}
function display_buttonval(mybutton){
alert("button value is: " + mybutton.value);
}
</script>
</head>
<body><b><hr>
<form name="simple_form">
<p>
Type your name here:
<input type="text" name="namestring" size="50">
<p>
<input type="button“ value="Print Form Stuff" onClick="display_formval(this.form);" >
<input type="button“ value="Print Button Stuff“ onClick="display_buttonval(this);" >
<input type="reset" value="Clear">
</form>
</body>
</html>
onClick on buttons – E13
<html>
<head>
<title>Event Handling and Forms</title>
<script language=javascript>
function greetme(message){alert(message);}
</script>
</head>
<body bgcolor=white>
<h2>Greetings Message</h2><hr>
<form>
<input type="button" value="Morning"
onClick="greetme('Good morning. This is your wakeup call!')">
<input type="button" value="Noon" onClick="greetme('Let\'s do lunch.')">
<input type="button" value="Night"
onClick="greetme('Have a pleasant evening.\nSweet dreams...')">
</form>
</body>
</html>
<html>
Event handlers and event methods – E14
<head><title>Event Handling</title>
<script language="JavaScript">
var tries=0;
function randomize(){
var now=new Date();
num=(now.getSeconds())%10; // Very cool!
num++;
}
function guessit(form){
if (form.tfield.value == num){
alert("Correct!!");
form.tfield.focus();
n=0;
randomize();
}
else{
tries++;
alert(tries + " Wrong. Try again.");
form.tfield.value=""; // Clear the text box
form.tfield.focus(); // Put the cursor in the text box
}
}
</script>
</head>
<body bgcolor="lightgreen" onLoad="randomize()"> <!-- Call function when page is loaded-->
<center><b>Pick a number between 1 and 10
<form name="myform">
<input type="textbox" size=4
name="tfield">
<p>
<input type="button"
name="button1"
value="Check my guess"
onClick="guessit(this.form)">
</form>
</body>
</html>
<html>
onFocus and onBlur events – E15
<head><title>Using the onFocus Event Handler</title>
<script language="JavaScript">
function handler(message){window.status = message; // Watch the status bar}
</script>
</head>
<body bgcolor="magenta"><b>The onFocus Event Handler<i>(When you click in one of the boxes, focus goes
to the status
bar)</i>
<form name="form1">
<p>Type your name:
<input type="text" name="namestring" size="50" onFocus="handler('Don\'t forget to enter your name')">
<p>Talk about yourself here:<br>
<textarea name="comments"
align="left"
onFocus="handler('Did you add comments?')"
rows="5" cols="50">I was born...
</textarea><p>
<input type="button“ value="submit">
<input type="reset" value="clear">
</form>
</body>
</html>
onChange event – E16
<html>
<head><title>onChange Event Handler</title></head>
<body>
<form>
Please enter your grade:
<input type="text" onChange="grade=parseInt(this.value);
if(grade < 0 || grade > 100){alert('Please enter a grade
between 0 and 100');}
else{confirm('Is '+ grade + ' correct?');}" >
</form>
</body>
</html>
<html>
onSubmit event – E17
<head><title>The onSubmit Event Handler</title>
<script language="JavaScript">
function popUp(){
newWin=window.open('','NewWin','toolbar=no,status=no,width=500,height=200');
newWin.document.write("<h3>Form data</h3>");
newWin.document.write("<b>Your name is:</b> " + document.form1.namestring.value);
newWin.document.write("<br><b>Your address is: </b>" + document.form1.address.value);
}
</script>
</head>
<body font="ariel" size=3>
<b> <hr>
<form name="form1" onSubmit="popUp();">
<p>
Type your name:
<input type="text" name="namestring" size="50">
<p>
Type in your address:
<input type="text" name="address“ size="80">
<p>
<input type="submit" value="Submit form">
<input type="reset" value="Clear">
</form>
</body>
</html>
onSubmit with return – E18
<html><title>Check it Out!</title>
<head>
<script language="JavaScript">
function okForm(form){
if (form.accept.checked == true){return true;}
else{
alert("Please check the box!");
form.accept.focus();
return false;
}
}
</script>
</head>
<body bgcolor="silver">
<font face="arial,helvitica" size=2>
<b>Thank you for your order. Check the box to continue.</b>
<form action="/cgi-bin/checkout.pl"method="post" onSubmit="return okForm(this)">
<input type="checkbox" name="accept" value="0" >
<input type="submit" value="Go to checkout" >
<input type="button" value="Go to Home Page" onClick="window.location.replace('http://localhost');" >
</form>
</body>
</html>
onKeyPress, onKeyDown – E19
<html>
<head><title>Key Events</title></head>
<body bgcolor="yellow" onKeyPress=" if(navigator.appName=='Netscape')
{alert('The key pressed:'+ event.which + 'ASCII '+ String.fromCharCode(event.which))}
else
{alert('The key pressed:'+ event.keyCode + 'ASCII '+ String.fromCharCode(event.keyCode));}">
<font face = "verdana">
<b>Press any key on your keyboard and see what happens!</b>
</body>
</html>
onKeyDown, onKeyUp – E20
<html>
<head><title>Key Events</title></head>
<body bgcolor="white"><font face="arial">
<center><img src="key.gif"></center>
<center><b><h2>Events</h2>
<h3><br>A <font color="blue">down </font>bouncing arrow will appear
when you press a key down<br>and a <font color=“blue">up </font>
jumping arrow appears when you release the key<br></b>
<form>
Type something while in the box:
<input type="text" size=10
onKeyDown="document.Arrow.src='images/down_arrow.gif'"
onKeyUp="document.Arrow.src='images/up_arrow.gif'">
<input type=reset value="reset">
</form>
<img src="images/up_arrow.gif" name="Arrow">
</body>
</html>
<html>
onError – E21
<head><title>Wake up call</title>
<script language="javascript">
function wakeupCall(){timeout=setTimeout('alert("Time to get up!")',2000);}
</script>
</head>
<body bgcolor="white">
<form>
<center>
<p>
<image src="Image/java_steam.gif“ onError="alert('Image is having trouble
loading!')">
<p>
<input type="button" value="Wake me" onClick="wakeupCall()">
</center>
</form>
</body>
</html>
Event properties – E22
<html>
<head><title>Event Properties</title></head>
<body bgcolor="yellow"
<font face = "verdana">
<form name="form1“ onSubmit="alert(event.type + ' ' + event.srcElement);">
<input type=button name="mybutton“ value="Click here"
onClick="alert(event.type + ' ' +event. srcElement);">
<input type=submit>
</form>
</body>
</html>