Javascript : Client Side Scripting :: Event Handling through JavaScript
About JavaScript Event? |
- 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 JavaScript functions.
- 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.
Examples of events
- A mouse click
- A web page or an image loading
- Mouse placing over a hot spot on the web page
- Selecting an input box in an HTML form
- Submitting an HTML form
- A keystroke
Note: Events are normally used in combination with functions, and the function will not be executed before the event occurs!
Event Methods |
onload and onUnload
- The onload and onUnload events are triggered when the user enters or leaves the page.
- The onload event is often used to check the visitor’s browser type and browser version, and load the proper version of the web page based on the information.
- Both the onload and onUnload events are also often used to deal with cookies that should be set when a user enters or leaves a page.
- For example, you could have a popup asking for the user’s name upon his first arrival to your page. The name is then stored in a cookie. Next time the visitor arrives at your page, you could have another popup saying something like: “Welcome James!”.
onFocus, onBlur and onChange
The onFocus, onBlur and onChange events are often used in combination with validation of form fields.
Example :- The checkEmail() function will be called whenever the user changes the content of the field:
<input type="text" size="30" class="nemail" onchange="checkEmail()">
onSubmit
The onSubmit event is used to validate ALL form fields before submitting it.
<form method="post" action="xxx.htm" onsubmit="return checkForm()">
onMouseOver and onMouseOut
onMouseOver and onMouseOut are often used to create “animated” buttons.
<a href="http://www.javaskool.com"
onmouseover="alert('You have placed Mouse on link'); return false">
<img src="images/JS_logo.png" width="100" height="30">
</a>
JavaScript Try…Catch Statement |
The try…catch statement allows you to test a block of code for errors.
Catching Errors in JavaScript
- When browsing Web pages on the internet, we all have seen a JavaScript alert box telling us there is a runtime error and asking “Do you wish to debug?”.
- Error message like this may be useful for developers but not for users. When users see errors, they often leave the Web page.
- So, how to trap and handle JavaScript error messages, so you don’t lose your audience.
- There are two ways of catching errors in a Web page:
- By using the try…catch statement (available in IE5+, Mozilla 1.0, and Netscape 6)
- By using the onerror event. This is the old standard solution to catch errors (available since Netscape 3)
Try…Catch Statement
The try…catch statement allows you to test a block of code for errors. The try block contains the code to be run, and the catch block contains the code to be executed if an error occurs.
Syntax :
try
{
//Run some code here
}
catch(err)
{
//Handle errors here
}
Code with bug | Code handling the bug |
---|---|
|
|
The Throw Statement
The throw statement allows you to create an exception. If you use this statement together with the try…catch statement, you can control program flow and generate accurate error messages.
Syntax
throw(exception)
Note :- The exception can be a string, integer, Boolean or an object.
Example
The example below determines the value of a variable called x. If the value of x is higher than 10 or lower than 0 we are going to throw an error. The error is then caught by the catch argument and the proper error message is displayed:
<html>
<body>
<script type="text/javascript">
var x=prompt("Enter a number between 0 and 10:","")
try
{
if(x>10)
throw "Err1"
else if(x<0)
throw "Err2"
}
catch(er)
{
if(er=="Err1")
alert("Error! The value is too high")
if(er == "Err2")
alert("Error! The value is too low")
}
</script>
</body>
</html>
The onerror Event
- Using the onerror event is the old standard solution to catch errors in a web page.
- The onerror event is fired whenever there is a script error in the page.
- To use the onerror event, you must create a function to handle the errors. Then you call the function with the onerror event handler. The event handler is called with three arguments: msg (error message), url (the url of the page that caused the error) and line (the line where the error occurred).
Syntax
onerror=handleErr
function handleErr(msg,url,l)
{
//Handle the error here
return true or false
}
Example
<html>
<head>
<script type="text/javascript">
onerror=handleErr
var txt=""
function handleErr(msg,url,l)
{
txt="There was an error on this page.\n\n"
txt+="Error: " + msg + "\n"
txt+="URL: " + url + "\n"
txt+="Line: " + l + "\n\n"
txt+="Click OK to continue.\n\n"
alert(txt)
return true
}
function message()
{
adddlert("Welcome guest!")
}
</script>
</head>
<body>
<input type="button" value="View message" onclick="message()" />
</body>
</html>
JavaScript Special Characters
- In JavaScript you can add special characters to a text string by using the backslash sign.
- Insert Special Characters
- The backslash (\) is used to insert apostrophes, new lines, quotes, and other special characters into a text string.
document.write ("You \& me are learning!")
output:
You & me are singing!
The table below lists other special characters that can be added to a text string with the backslash sign
Code | Outputs |
---|---|
\’ | single quote |
\" | double quote |
\& | ampersand |
\\ | backslash |
\n | new line |
\r | carriage return |
\t | tab |
\b | backspace |
\f | form feed |
Download Examples |
Click Here to download Example2
Click Here to download Example3
Recent Comments