You are on page 1of 15

Basics of Web Development JavaScript Part 3

Event Handler Events are the beating heart of any JavaScript application. On this page I give an overview of what event handling is, what its problems are and how to write proper cross-browser scripts. Without events there are no scripts. Take a look at any web page with JavaScript in it: in nearly all cases there will be an event that triggers the script. The reason is very simple. JavaScript is meant to add interactivity to your pages: the user does something and the page reacts. Therefore JavaScript needs a way of detecting user actions so that it knows when to react. It also needs to know which functions to execute, functions that do something that you, the web developer, have judged likely to increase the appeal of your pages. These pages describe the best way to write such scripts. It isnt easy, but it is very satisfying work. When the user does something an event takes place. There are also some events that arent directly caused by the user: the load event that fires when a page has been loaded, for instance. The event handler waits until a certain event, for instance a click on a link, takes place. When it happens it handles the event by executing some JavaScript you have defined. So in short we can say that by using JavaScript, we have the ability to create dynamic web pages. Events are actions that can be detected by JavaScript. Every element on a web page has certain events which can trigger a JavaScript. For example, we can use the onClick event of a button element to indicate that a function will run when a user clicks on the button. We define the events in the HTML tags. Note: Events are normally used in combination with functions, and the function will not be executed before the event occurs! The following table demonstrates the complete reference of the events recognized by JavaScript.

nah@puv.fi

Page 1

Complete list of Event handlers in Javascript Event Handler


onAbort onBlur
Image Button, Checkbox, FileUpload, Layer, Password, Radio, Reset, Select, Submit, Text, TextArea, Window FileUpload, Select, Text, TextArea Button, Document, Checkbox, Link, Radio, Reset, Submit Document, Link Window Image, Window Button, Checkbox, FileUpload, Layer, Password, Radio, Reset, Select, Submit, Text, TextArea, Window Document, Image, Link, TextArea Document, Image, Link, TextArea Document, Image, Link, TextArea Image, Window Button, Document, Link

Used with

Triggered when:
The loading of the image is cancelled. The object in question loses focus (e.g. by clicking outside it or pressing the TAB key). The data in the form element is changed by the user. The object is clicked on. The object is double-clicked on. An icon is dragged and dropped into the browser. A JavaScript error occurs. The object in question gains focus (e.g. by clicking on it or pressing the TAB key). The user presses a key. The user presses or holds down a key. The user releases a key. The whole page has finished loading. The user presses a mouse button. The user moves the mouse The user moves the mouse away from the object. The user moves the mouse over the object. The user releases a mouse button The user moves the browser window or frame. The user clicks the form's Reset button. The user resizes the browser window or frame. The user selects text within the field. The user clicks the form's Submit button. The user leaves the page.

onChange onClick onDblClick onDragDrop onError onFocus

onKeyDown onKeyPress onKeyUp onLoad onMouseDown onMouseMove onMouseOut onMouseOver onMouseUp onMove onReset onResize onSelect onSubmit onUnload

None
Image, Link Image, Link Button, Document, Link Window Form Window Text, Textarea Form Window

nah@puv.fi

Page 2

Here we will see some examples about JavaScript event handler.

onChange:
The onChange Event Handler executes JavaScript code when input focus exits the field after the user modifies its text. <head> <script type=javascript> function valid(input) { alert("You have changed the value from 10 to " + input); } </script> </head> <body> <H3>Example of onChange Event Handler</H3> Try changing the value from 10 to something else:<BR> <FORM> <INPUT TYPE="text" VALUE="10" onChange="valid(this.value)"> </FORM> </body> In this example, 'data' is a text field. When a user attempts to leave the field after a change of the original value, the onChange Event Handler calls the valid() function which alerts the user about value that has been inputted.

onClick:
In an onClick Event Handler, JavaScript function is called when an object in a button (regular, radio, reset and submit) is clicked, a link is pushed, a checkbox is checked or an image map area is selected. Except for the regular button and the area, the onClick Event Handler can return false to cancel the action. For example: <html> <head> <script language=Javascript> function valid(form) { var input = form.data.value; alert("Hello " + input + " ! Welcome..."); }
nah@puv.fi Page 3

</script> </head> <body> <h3>Click on the button after inputting your name into the text box:</h3><br> <form> <input type="text" name="data"> <input type="button" value="Click Here" onClick="valid(this.form)"> </form> </body> </html> In this example, when the user clicks the button "Click Here", the onClick Event Handler calls the function valid().

onError:
An onError Event Handler executes JavaScript code when an error occurs while loading a document or an image. With onError event now you can turn off the standard JavaScript error messages and have your own function that will trace all the errors in the script. To disable all the standard JavaScript error messages, all you need to do is set window.onerror = null. To call a function when an error occurs all you need to do is this: onError = "myerrorfunction()". <html> <head> <script language=Javascript> window.onerror = ErrorSetting; var e_msg = ""; var e_file = ""; var e_line = ""; document.form[8].value = "myButton"; // This is the error function ErrorSetting(msg, file_loc, line_no) { e_msg = msg; e_file = file_loc; e_line = line_no; return true; } function display() { var error_d = "Error in file: " + e_file + "\nline number:" + e_line + "\nMessage:" + e_msg; alert("Error Window:\n" + error_d); }
nah@puv.fi Page 4

</script> </head> <body> <h3>Example of onError Event Handler</h3> <form> <input type="button" value="Show the error" onClick="display()"> </form> </body>

Notice that the function ErrorSetting() takes three arguments: message text, URL and Line number of the error line. So all we did was invoke the function when an error occurred and set these values to three different variables. Finally, we displayed the values via an alert method. Note: If you set the function ErrorSetting() to false, the standard dialog will be seen.

onFocus:
An onFocus Event Handler executes JavaScript code when input focus enters the field either by tabbing in or by clicking but not selecting input from the field. For windows, frames and framesets the Event Handler executes JavaScript code when the window gets focused. In windows you need to specify the Event Handler in the <BODY> attribute. For example: <html> <head> <script language=Javascript> function onFocusFunc(){ alert("You focused in the textbox!!"); } </script> </head> <body> <h3>Example of onFocus Event Handler</h3> <form> <input type="text" onFocus="onFocusFunc()"> </form> </body> </html>

nah@puv.fi

Page 5

In the above example, when you put your mouse on the text box, an alert() message displays a message.

onLoad:
An onLoad event occurs when a window or image finishes loading. For windows, this Event Handler is specified in the <BODY> attribute of the window. In an image, the Event Handler will execute handler text when the image is loaded. For example: <html> <head> <script language=Javascript> function onLoadFunc(){ alert("Event Handler onLoad Example!"); } </script> </head> <body onload="onLoadFunc()"> <h3>Example of onLoad Event Handler</h3> </body> </html> The example shows how the function hello() is called by using the onLoad Event Handler.

onMouseOut: JavaScript code is called when the mouse leaves a specific link or an object or area from outside that object or area. For area object the Event Handler is specified with the <AREA> tag. <html> <head> <script language=Javascript> </script> </head>

nah@puv.fi

Page 6

<body> <h3>Example of onMouseOut Event Handler</h3> Put your mouse over <a href="javascript:void('');" onMouseOut="window.status='You left the link!'; return true;"> here </a> and then take the mouse pointer away. </body> </html> In the above example, after pointing your mouse and leaving the link , the text "You left the link!" appears on your window's status bar.

onMouseOver:
JavaScript code is called when the mouse is placed over a specific link or an object or area from outside that object or area. For area object the Event Handler is specified with the <AREA> tag. For example: <html> <head> <script language=Javascript> </script> </head> <body> <h3>Example of onMouseOver Event Handler</h3> Put your mouse over <a href="javascript:void('');" onMouseOver="window.status='Hello!How are you?'; return true;"> here </a> and look at the status bar (Usually at the bottom of your browser window.) </body> </html>

In the above example when you point your mouse to the link, the text "Hello! How are you?" appears on your window's status bar.

nah@puv.fi

Page 7

onReset:
A onReset Event Handler executes JavaScript code when the user resets a form by clicking on the reset button. <html> <head> <script language=Javascript> </script> </head> <body> <h3>Example of onReset Event Handler</h3> Please type something in the text box and press the reset button:<br> <form onReset="alert('This will reset the form!')"> <input type="text"> <input type="reset" value="Reset Form" > </form> </body> </html>

In the above example, when you push the button, "Reset Form" after typing something, the alert method displays the message, "This will reset the form!"

onSelect:
A onSelect Event Handler executes JavaScript code when the user selects some of the text within a text or textarea field. <html> <head> <script language=Javascript> </script> </head> <body> <h3>Example of onSelect Event Handler</h3> Select the text from the text box:<br>

nah@puv.fi

Page 8

<form> <input type="text" value="Select This" onSelect="alert('This is an example of onSelect!!')"> </form> </body> </html> In the above example, when you try to select the text or part of the text, the alert method displays the message, "This is an example of onSelect!!".

onSubmit:
An onSubmit Event Handler calls JavaScript code when the form is submitted. <html> <head> <script language=Javascript> </script> </head> <body> <h3>Example of onSubmit Event Handler</h3> Type your name and press the button<br> <form name="myForm" onSubmit="alert('Thank You' + myForm.data.value + '!')"> <input type="text" name="data"> <input type="submit" value="Submit this form"> </form> </body> </html>

In this example, the onSubmit Event Handler calls an alert() function when the button "Submit this form" is pressed.

nah@puv.fi

Page 9

onUnload:
An onUnload Event Handler calls JavaScript code when a document is exited. <html> <head> <script type="text/javascript"> function onUnload(){ alert("Thanks for Visiting!"); } </script> </head> <body onUnLoad="onUnload()"> <h3>Example of onUnload Event Handler</h3> Close the window and look what happens when you try to leave this page ... </body> </html> In this example, the onUnload Event Handler calls the onUnload() function as user exits a document.

Exception Handling

It is impossible for a programmer to write a program without errors. Programming languages include exceptions, or errors, that can be tracked and controlled. Exception handling is a very important concept in programming technology. In earlier versions of JavaScript, the exceptions handling was not so efficient and programmers found it difficult to use. Later versions of JavaScript resolved this difficulty with exceptions handling features like try..catch handlers, which presented a more convenient solution for programmers of JavaScript. Therefore we can't always prevent errors from occurring, but we can do something about to handle them. The JavaScript "Try... Catch" statement helps us to handle JavaScript errors in a very "nice" way. To use the JavaScript Try... Catch statement, we take any JavaScript code we think could potentially result in an error, and wrap it within the JavaScript "try" statement. We then code what we want to happen in the JavaScript event of an error and wrap that in a JavaScript "catch" statement.

nah@puv.fi

Page 10

Syntax of JavaScript Try Catch Statement: <script type="text/javascript"> try { //Your JavaScript code will be here. } catch(err) { //JavaScript Errors handling code will be here } </script>

Here lets see a simple example:

<html> <head> <script type="text/javascript"> try { document.write(junkVariable) } catch(err) { document.write(err.message + "<br/>") } </script> </head> <body> </body> </html>

Where in this example the variable junkVariable is undefined and the usage of this in try block gives an error. The control is transferred to the catch block with this error and this error message is printed in the catch block.

nah@puv.fi

Page 11

Another Example: <html> <head> <script type="text/javascript"> function welcome(){ try{ document.write("Well Come " + username); } catch (err) { document.write ("There are some errors on this page while loading...<br>"); document.write("Error is : " + err.description + " <br>Error number is " + err.number); } } </script> </head> <body onLoad="welcome()"> </body> </html> The throw Statement You can use throw statement to raise your built-in exceptions or your customized exceptions. Later these exceptions can be captured and you can take an appropriate action. Following is the example showing usage of throw statement. <head> <script type="text/javascript"> function myFunc() { var a = 100; var b = 0; try{ if ( b == 0 ){ throw( "Divide by zero error." ); }else{ var c = a / b; } }catch ( e ) { alert("Error: " + e ); } } </script> </head>
nah@puv.fi Page 12

<body> <p>Click the following to see the result:</p> <form> <input type="button" value="Click Me" onclick="myFunc();"/> </form> </body> You can raise an exception in one function using a string, integer, Boolean or an object and then you can capture that exception either in the same function as we did above, or in other function using try...catch block.

Another Example In following example by pressing the button, a JavaScript Function will be call. On calling that function document.writes try to print "JavaScript Examples" but in JavaScript there is no function with the name of document.writes so an error will be generate that is handled by the try catch statement of JavaScript here. Catching the error will be in kind of user response to continue the remaining page loading or redirect to the home page of Vaasa University of Applied Sciences. <html> <head> <script language="javascript"> function handleError(){ try{ document.writes("JavaScript Exception handling!"); }catch(exception){ err=exception + "\n"; err+=exception.description + " Error\n"; err+="There is an error at this page.\n"; err+="Click OK to continue viewing this page,\n"; err+="or Cancel to return to the school website.\n"; if(!confirm(err)){ document.location.href="http://www.puv.fi/"; } } } </script> </head> <body> <input type="button" value="Click to Handle Errors" onclick="handleError()"> </body> </html>

nah@puv.fi

Page 13

The onerror() Method

The onerror event handler was the first feature to facilitate error handling for JavaScript. The error event is fired on the window object whenever an exception occurs on the page. The onerror event handler provides three pieces of information to identify the exact nature of the error: Error message . The same message that the browser would display for the given error URL . The file in which the error occurred Line number . The line number in the given URL that caused the error In Following example by pressing the button, a JavaScript Function will be call. On calling that function document.writes try to print "JavaScript Examples" but in JavaScript there is no function with the name of document.writes so an error will be generate that is handled by JavaScript onerror error handler. JavaScript onerror handler takes a function to handle any error at the page this function gets three arguments first is Error Message second is URL of page where the error has been occurred and the last argument is returning the line number where the error was occurred.

<html> <head> <script language="javascript"> onerror=errorHandler; var error=""; function errorHandler(errMessage,url,line){ error="There is an error at this page.\n"; error+="Error: " + errMessage+ "\n"; error+="URL: " + url + "\n"; error+="Line: " + line + "\n\n"; error+="Click OK to continue viewing this page,\n"; alert(error); return true; } function handleError(){ document.writes("JavaScript Examples"); } </script> </head> <body> <input type="button" value="Click to Handle Errors" onclick="handleError()"> </body> </html>

nah@puv.fi

Page 14

One more similar example <html> <head> <script type="text/javascript"> window.onerror = function (msg, url, line) { alert("Message : " + msg ); alert("url : " + url ); alert("Line number : " + line ); } </script> </head> <body> <p>Click the following to see the result:</p> <form> <input type="button" value="Click Me" onclick=" myFunc()" /> </form> </body> </html>

Also You can use onerror method to show an error message in case there is any problem in loading an image as follows: <img src="myimage.gif" onerror="alert('An error occurred loading the image.')" /> Furtheremore You can use onerror with many HTML tags to display appropriate messages in case of errors.

nah@puv.fi

Page 15

You might also like