Tuesday, August 28, 2012

JavaScript Try...Catch Statement


The try...catch statement allows you to test a block of code for errors.

JavaScript - Catching Errors

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.
This chapter will teach you how to catch and handle JavaScript error messages, so you don't lose your audience.

The 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
  }

Note that try...catch is written in lowercase letters. Using uppercase letters will generate a JavaScript error!

Examples

The example below is supposed to alert "Welcome guest!" when the button is clicked. However, there's a typo in the message() function. alert() is misspelled as adddlert(). A JavaScript error occurs. The catch block catches the error and executes a custom code to handle it. The code displays a custom error message informing the user what happened:

Example

<!DOCTYPE html>
<html>
<head>
<script>
var txt="";
function message()
{
try
  {
  adddlert("Welcome guest!");
  }
catch(err)
  {
  txt="There was an error on this page.\n\n";
  txt+="Error description: " + err.message + "\n\n";
  txt+="Click OK to continue.\n\n";
  alert(txt);
  }
}
</script>
</head>

<body>
<input type="button" value="View message" onclick="message()" />
</body>

</html>

Try it yourself »

The next example uses a confirm box to display a custom message telling users they can click OK to continue viewing the page or click Cancel to go to the homepage. If the confirm method returns false, the user clicked Cancel, and the code redirects the user. If the confirm method returns true, the code does nothing:

Example

<!DOCTYPE html>
<html>
<head>
<script>
var txt="";
function message()
{
try
  {
  adddlert("Welcome guest!");
  }
catch(err)
  {
  txt="There was an error on this page.\n\n";
  txt+="Click OK to continue viewing this page,\n";
  txt+="or Cancel to return to the home page.\n\n";
  if(!confirm(txt))
    {
    document.location.href="http://www.w3schools.com/";
    }
  }
}
</script>
</head>

<body>
<input type="button" value="View message" onclick="message()" />
</body>

</html>

Try it yourself »


The throw Statement

The throw statement can be used together with the try...catch statement, to create an exception for the error. Learn about the throw statement in the next chapter.

JavaScript Events


Events are actions that can be detected by JavaScript.

Example

Mouse Over Me
Click Me

Events

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.
Examples of events:
  • Clicking a button (or any other HTML element)
  • A page is finished loading
  • An image is finished loading
  • Moving the mouse-cursor over an element
  • Entering an input field
  • Submitting a form
  • A keystroke
To see all events recognized by JavaScript, go to our Complete Event Reference.
Events are normally used in combination with functions.

HTML Event Attributes

To assign events to HTML elements you can use the event attributes.
For a complete list of all available event attributes, go to our Complete Event Reference.

Example

Assign an onclick event to a button element:
<button id="myBtn" onclick="displayDate()">Try it</button>

Try it yourself »

In the example above, a function named displayDate will be executed when the button is clicked.

Assign Events Using the HTML DOM

You can assign events to HTML elements within a script or a function:

Example

Assign an onclick event to a button element:
<script>

document.getElementById("myBtn").onclick=function(){displayDate()};

</script>

Try it yourself »

In the example above, a function named displayDate will be executed when the button is clicked.

onload and onunload

The onload and onunload events are triggered when the user enters or leaves the page.

The onload event can be used to check the visitor's browser type and browser version, and load the proper version of the web page based on the information.

The onload and onunload events can be used to deal with cookies.

Example

<body onload="checkCookies()" />

Try it yourself »

onfocus, onblur and onchange

The onfocus, onblur and onchange events are often used in combination with validation of form fields.
Below is an example of how to use the onchange event. The checkEmail() function will be called 
whenever the user changes the content of the field:

<input type="text" onchange="checkEmail()" />

onsubmit

The onsubmit event can be used to validate form fields before submitting it.

Below is an example of how to use the onsubmit event. The checkForm() function will be called when 
the user clicks the submit button in the form. If the field values are not accepted, the submit should be cancelled.

<form method="post" action="mySubmit.asp" onsubmit="checkForm()">

onmouseover, onmouseout

The onmouseover and onmouseout events can be used to trigger a function when the user mouses over, or out of, an HTML element.

Example

A simple onmouseover-onmouseout example:
Mouse Over Me

Try it yourself »

onmousedown, onmouseup and onclick

The onmousedown, onmouseup, and onclick events are all parts of a mouse-click. First when a mouse-button is clicked, the onmousedown event is triggered, then, when the mouse-button is released, the onmouseup event is triggered, finally, when the mouse-click is completed, the onclick event is triggered.

Example

A simple onmousedown-onmouseup example:
Click Me

Try it yourself »


JavaScript For...In Statement


JavaScript For...In Statement

The for...in statement loops through the properties of an object.

Syntax

for (variable in object)
  {
  code to be executed
  }

Note: The block of code inside of the for...in loop will be executed once for each property.

Example

Looping through the properties of an object:

Example

var person={fname:"John",lname:"Doe",age:25};

for (x in person)
  {
  txt=txt + person[x];
  }

Try it yourself »

JavaScript Break and Continue Statements


The break Statement

The break statement will break the loop and continue executing the code that follows after the loop (if any).

Example

for (i=0;i<10;i++)
  {
  if (i==3)
    {
    break;
    }
  x=x + "The number is " + i + "<br />";
  }

Try it yourself »


The continue Statement

The continue statement will break the current iteration and continue the loop with the next value.

Example

for (i=0;i<=10;i++)
  {
  if (i==3)
    {
    continue;
    }
  x=x + "The number is " + i + "<br />";
  }

Try it yourself »