Professional Documents
Culture Documents
JavaScript Function
A function is a group of reusable code which can be called anywhere in your program. This
eliminates the need of writing the same code again and again. It helps programmers in writing
modular codes. Functions allow a programmer to divide a big program into a number of small
and manageable functions.
Like any other advanced programming language, JavaScript also supports all the features
necessary to write modular code using functions
JavaScript allows us to write our own functions as well.
Function Definition
Before we use a function, we need to define it. The most common way to define a function in
JavaScript is by using the function keyword, followed by a unique function name, a list of
parameters (that might be empty), and a statement block surrounded by curly braces.
Syntax
The basic syntax is shown here.
<script type = "text/javascript">
function functionname(parameter-list) {
statements
}
</script>
Example
It defines a function called sayHello that takes no parameters –
<script type = "text/javascript">
function sayHello() {
alert("Hello there");
}
</script>
Calling a Function
To invoke a function, you would simply need to write the name of that function as shown in the
following code.
Example
<html>
<head>
<script type = "text/javascript">
function sayHello() {
document.write ("Welcome to JMC!");
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type = "button" onclick = "sayHello()" value = "Say Hello">
</form>
<p>Use different text in write method and then try...</p>
</body>
</html>
1
Output
Function Parameters
We have seen functions without parameters. But there is a facility to pass different parameters
while calling a function. These passed parameters can be captured inside the function and any
manipulation can be done over those parameters. A function can take multiple parameters
separated by comma.
Example
We have modified our sayHello function here. Now it takes two parameters.
<html>
<head>
<script type = "text/javascript">
function sayHello(name, age) {
document.write (name + " is " + age + " years old.");
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type = "button" onclick = "sayHello('Vimala', 35)" value = "Say Hello">
</form>
<p>Use different parameters inside the function and then try...</p>
</body>
</html>
2
Output
3
Output
JavaScript Events
JavaScript's interaction with HTML is handled through events that occur when the user or
the browser manipulates a page.
When the page loads, it is called an event. When the user clicks a button, that click too is
an event. Other examples include events like pressing any key, closing a window,
resizing a window, etc.
Developers can use these events to execute JavaScript coded responses, which cause
buttons to close windows, messages to be displayed to users, data to be validated, and
virtually any other type of response imaginable.
Events are a part of the Document Object Model (DOM) Level 3 and every HTML
element contains a set of events which can trigger JavaScript Code.
onclick Event Type
This is the most frequently used event type which occurs when a user clicks the left button of his
mouse. You can put your validation, warning etc., against this event type.
Example
<html>
<head>
<script type = "text/javascript">
function sayHello() {
alert("Hello World")
}
</script>
</head>
<body>
<p>Click the following button and see result</p>
<form>
<input type = "button" onclick = "sayHello()" value = "Say Hello" />
</form>
</body>
</html>
4
Output
5
Example
<head>
<script type="text/javascript">
function OnMouseIn (elem) {
elem.style.border = "2px solid blue";
}
function OnMouseOut (elem) {
elem.style.border = "";
}
</script>
</head>
<body>
<div style="background-color:#d0f0a0; width:200px"
onmouseover="OnMouseIn (this)" onmouseout="OnMouseOut (this)">
Move your mouse pointer into and out of this element!
</div>
</body>
Output
6
Onchange script Triggers when an element changes
Onclick script Triggers on a mouse click
oncontextmenu script Triggers when a context menu is triggered
Ondblclick script Triggers on a mouse double-click
Ondrag script Triggers when an element is dragged
Ondragend script Triggers at the end of a drag operation
7
onloadeddata script Triggers when media data is loaded
Triggers when the duration and other
onloadedmetadata script
media data of a media element is loaded
Triggers when the browser starts to load
onloadstart script
the media data
onmessage script Triggers when the message is triggered
onmousedown script Triggers when a mouse button is pressed
onmousemove script Triggers when the mouse pointer moves
8
Onredo script Triggers when the document performs a
redo
Onresize script Triggers when the window is resized
Triggers when an element's scrollbar is
Onscroll script
being scrolled
Triggers when a media element's seeking
onseeked script attribute is no longer true, and the seeking
has ended
Triggers when a media element's seeking
onseeking script
attribute is true, and the seeking has begun
Onselect script Triggers when an element is selected
Triggers when there is an error in fetching
Onstalled script
media data
9
When a syntax error occurs in JavaScript, only the code contained within the same thread as the
syntax error is affected and the rest of the code in other threads gets executed assuming nothing
in them depends on the code containing the error.
Runtime Errors
Runtime errors, also called exceptions, occur during execution (after compilation/interpretation).
For example, the following line causes a runtime error because here the syntax is correct, but at
runtime, it is trying to call a method that does not exist.
<script type = "text/javascript">
window.printme();
</script>
Exceptions also affect the thread in which they occur, allowing other JavaScript threads to
continue normal execution.
Logical Errors
Logic errors can be the most difficult type of errors to track down. These errors are not the result
of a syntax or runtime error. Instead, they occur when you make a mistake in the logic that drives
your script and you do not get the result you expected.
You cannot catch those errors, because it depends on your business requirement what type of
logic you want to put in your program.
The try...catch...finally Statement
The latest versions of JavaScript added exception handling capabilities. JavaScript implements
the try...catch...finally construct as well as the throwoperator to handle exceptions.
You can catch programmer-generated and runtime exceptions, but you cannot catch JavaScript
syntax errors.
Here is the try...catch...finally block syntax –
<script type = "text/javascript">
try {
[break;]
}
catch ( e ) {
[break;]
}
[ finally {
}]
</script>
The try block must be followed by either exactly one catch block or one finally block (or one of
both).
Now let us try to catch this exception using try...catch and display a user-friendly message.
<html>
<head>
<script type = "text/javascript">
function myFunc() {
var a = 100;
try {
alert("Value of variable a is : " + a );
}
catch ( e ) {
alert("Error: " + e.description );
}
}
10
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type = "button" value = "Click Me" onclick = "myFunc();" />
</form>
</body>
</html>
Output
You can use finally block which will always execute unconditionally after the try/catch. Here is
an example.
<html>
<head>
<script type = "text/javascript">
function myFunc() {
var a = 100;
try {
alert("Value of variable a is : " + a );
}
catch ( e ) {
alert("Error: " + e.description );
}
finally {
alert("Finally block will always execute!" );
}
}
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type = "button" value = "Click Me" onclick = "myFunc();" />
</form>
</body>
11
</html>
Output
12
Output
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
Here is the example to show how to extract this information.
13
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>
Output
You can display extracted information in whatever way you think it is better.
You can use an onerror method, as shown below, to display an error message in case there is
any problem in loading an image.
<img src="myimage.gif" onerror="alert('An error occurred loading the image.')" />
You can use onerror with many HTML tags to display appropriate messages in case of errors.
14