17 JavaScript and Event Handling

Dr M. Vijayalakshmi

JavaScript – Event Handlers

 

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. It allows us to execute an action of code when the event occurs. All the event handlers in JavaScript start with the keyword on, and each event handler deals with a certain type of event. (For eg, onClick )

 

How it works:

 

Step 1:    User moves mouse over object

Step 2:   Event senses that something happened to the object

Step 3:   JavaScript (Event handler) tells the object what to do

Step 4:   Using DOM, the handler locates the object on the web page

Step 5:   Object’s image source is changed

Here Step is an action where the user moves the mouse over an object. This action is sensed as an event, and JavaScript handles this event with an event handler. Using DOM, the object is located and the reaction to the event is performed as toggling the source image to anaother one. This is shown in the below diagram.

 

The following is the list of event handlers described along with the Objects on which they can be applied and when they are triggered as given in Table 19.1.

 

TABLE 19.1: Event Handlers

 

 

Now let us demonstrate some of the event type with examples and the output of it.

 

onClick Event Type

 

This event occurs when a user clicks the left button of his mouse.

 

Example 1

 

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

  On clicking the button it calls the function sayHello() which alerts a message as shown in FIgure 19.1 and Figure 19.2.

 

Output:

 

Example 2

 

<html>

<head>

<title> color world </title>

<script language = “JAVASCRIPT”>

function color(f, a)

{

document.bgColor=a;

alert(a);

}

</script>

</head>

<body bgcolor=gray>

<form name=myform>

<input type = button value=red onClick=color(this.form,”RED”)>

<input type = button value=orange onClick=color(this.form,”ORANGE”)> <input type = button value=green onClick=color(this.form,”GREEN”)> <input type = button value=violet onClick=color(this.form,”VIOLET”)> </form>

</body>

</html>

 

This example is to demonstrate the onClick event type which changes the background color of the document on clicking the respective buttons as shown in Figure 19.3 and Figure 19.4.

 

Output

 

 

 

     onSubmit Event type

 

The onSubmit is an event that occurs when you try to submit a form.

Syntax

<html>

<head>

<script type=”text/javascript”>

function validate()

{

all validation goes here

………

return either true or false

}

</script>

</head>

<body>

<form method=”POST” action=”t.cgi” onsubmit=”return validate()”> <input type=”submit” value=”Submit” />

</form>

</body>

</html>

 

The example demonstates that the form is validated when a submit button is clicked as shown in Figure 19.5.

    Output:

onMouseOver and onMouseOut Event

 

 

The onMouseOver event is triggered when you bring your mouse over any element on the document and the onMouseOut event is triggered when you move your mouse out from that element.

 

Example 1:

 

<html>

<head>

<script type=”text/javascript”>

function over() {

document.write (“Mouse Over”);

}

function out() {

document.write (“Mouse Out”);

}

</script>

</head>

<body>

<p>Bring your mouse inside the division to see the result:</p>

<div onmouseover = “over()” onmouseout= “out()“ > <h2> This is inside the division </h2>

</div>

</body>

</html>

 

This example demonstrates the onmouseover and onmouseout event types. When the mouse is moved over the text, the function over() is called which displays the message “Mouse Over” and when the mouse is moved out of the text , the function out() is called which displays the message “Mouse Out”. The output of this example code is shown in the Figure 19.6 and Figure 19.7.

 

Output:

 

 

Example 2:

 

<html>

<head>

<title> image world </title>

</head>

<body >

<a href=ex.html onMouseOver = document.images[0].src = “FLOWER.jpg”

onMouseOut = document.images[0].src = “GRAPES.jpg” > <img src=”GRAPES.jpg” wi dth=160 height=100 border=1> </a>

</body>

</html>

 

This example toggles the image on thedocument when the mouse is moved over or moved out of the image displayed. The output of this example code is shown in Figure 19.8 and Figure 19.9.

 

Output:

 

Figure 19.9

 

JavaScript Form Validation

 

HTML form validation can be done by writing a script code using JavaScript.

   

Example:

 

An example to validate the name to be filled out without leaving it blank is shown below.

function validateForm() {

var x = document.forms[“myForm”][“fname”].value; if (x == null || x == “”) {

alert(“Name must be filled out”);

return false;

}

}

 

JavaScript Forms

 

<form name=”myForm” action=”demo_form.asp” onsubmit=”return validateForm()” method=”post”>

Name: <input type=”text” name=”fname”>

<input type=”submit” value=”Submit”>

</form>

 

Example 1:

 

<html>

<head>

<script type=”text/javascript”>

function newValue()

{

var x=document.forms.myForm

x[0].value=”The mere act of aiming at something makes you big”

x[0].select()

}

</script>

</head>

<body>

<body>

<form name=”myForm”>

<textarea name=”myTextarea” rows=”10″ cols=”20″> The roots of e ducation are bitter but the fruit is sweeter </textarea><br />

<input type=”button” onclick=”newValue()” value=”New Value”> </form></body></html>

This example is to demonstrate about validating a form which has a textarea. The textarea is initially shown with the text. On clicking the button, the function newValue() is called which displays another text. The method select() is used to display the textarea as selected. The output is shown in FIgure 19.10.

 

Output:

 

     Example 2:

 

<html>

<head>

<title> Forms</title>

<!–This code checks the Checkbox When the button is clicked –>

<script Language=’JavaScript’>

function Chk(f1)

{

f1.Check.checked=true;

window.alert(“The Checkbox just got checked”);

f1.Check.checked=false;

f1.Radio[0].checked=true;

f1.Radio[1].checked=false;

window.alert(“The Radio button just got checked”);

}

</script>

</head>

<body>

<form>

Client Name :        <Input Type =Text Name=”Text” Value=””><br><br>

Client Address : <Input Type =Text Name=”Text1″ Value=””><br><br> Client E-mail Address : <Input Type =Text Name=”Text2″ Value=””><br><br> <Input Type=”radio” Name=”Radio” Value=””> Male

<Input Type=”radio” Name=”Radio” Value=””> Female<br><br>

<Input Type=“checkbox” Name=”Check” Value=””> Em ploye d <br><br> <Input Type=”Button” Name=”Bt” Value=”Set Element Array Value”

onClick=”Chk(this.form)”>

</form>

</body>

</html>

This example is to demonstrate about validating a form which has a checkbox or a radiobutton. If checkbox is checked or radiobutton is checked, the property “checked” is made true and it will display the message as checked. The output is shown in Figure 19.11.

 

Output:

 

 

Example 3:

 

<html>

<head>

<script language=”javascript”>

</script>

</head>

<body>

<form>

FirstName:<input type=”text” name=”Firstname” size=20 onFocus=”this.blur();”>

LastName:<input type=”text” name=”Lastname” size=20><p>

Address:<input type=”text” name=”Address” size=60><p> pincode:<input type=”text” name=”Pincode” size=6><p> <input type=”button” name=”act” value=”verify”> </form>

</body>

</html>

 

This example code demonstrates the use of function onFocus on a textfield. When a focus is gained on the textfield, it is made to blur using the function blur() which will not allow to enter any data in the textfield. The output is shown in Figure 19.12.

 

Output:

 

 

Example 4:

 

<html>

<head>

<title>forms1</title>

<script>

function func(f1)

{

alert(“the form elements have been cleared”);

}

</script>

</head>

<body>

<form onReset=”func(this.form)”>

Client Name: <input type=”text” name=”text” value=””><br><br>

Client address: <input type=”text” name=”text1″ value=””><br><br> <input type=”radio” name=”radio” value=””>male

<input type=”radio” name=”radio” value=””>female<br><br>

<input type=”checkbox” name=”check” value=””>employed<br><br> <input type=”reset” name=”rst” value=”reset”>

</form>

</body>

</html>

 

This example code demonstrates validating a form on a reset button. The event onReset is triggered when a reset button is clicked which clears the form content and displays the message as cleared. The output is shown in Figure 19.13

    Output:

 

Example 5:

 

<html>

<head>

<title> using text and button objects</title>

<script language=”javascript”>

function calculate(form)

{

form.results.value= eval(form.entry.value * 10 );

}

</script>

</head>

<body>

<form>

<input type=”text” name=”entry” value=””>

<input type=”button” value=”calculate” onClick=”calculate(this.form);”

<br>

<input type=”text” name=”results” onFocus=”this.blur();”> <br>

</form>

</body>

</html>

This example code demonstrates the use of onClick() and onFocus(). The onFocus is applied on results textfield which will not allow to enter any value using the blur() method. The value entered on the entry field is calculated and shown in the result field. The output of this code is shown in Figure 19.14.

 

Output:

 

 

Example 6:

 

<htMl>

<head>

<title>working with checkboxes</title>

<script>

function calculate(form, callingField)

{

if(callingField==”result”)

{

if(form.square.checked)

{

form.entry.value= Math.sqrt(form.result.value);

}

else

{

form.entry.value=form.result.value/2;

}

}

else {

if(form.square.checked)

{

form.result.value = form.entry.value * form.entry.value;

}

Else {

form.result.value = form.entry.value*2;

}

}}

</script>

</head>

<body>

<form>

<center><br>

<b> value: </b>

<input type =”text” name = “entry” value = 0 onChange =”calculate(this.form,this.name);”> <br><br>

<b>action</b>(default-double):

<input type =”checkbox” name = “square” onClick = “calculate(this.form,this.name);”>square <br><br>

<b> result: </b>

<input type =”text” name = “result” value = 0 onChange = “calculate(this.form,this.name);”> </center>

</form>

</body>

</html>

This example code demonstrates the use of onClick and onChange event types. There are two textfields (entry and result) and a radiobutton in the form. If the calling field is result field, and if the checkbox is checked then it calculates the squareroot of the value entered in the result field and displays in the entry field else it calculates half of the result value and displays in the entry field. Similarly when the value entered in the entry field changes, based on the checkbox checked or not checked displays the square of the value entered in the entry field or multiplies the value by 2 and displays in the result field. The output of this code is shown in Figure 19.15.

    Output:

 

     JavaScript Cookies

 

A cookie is used to store information on the user’s computer even when the user switches off his/her computer. It is a data that is sent from a web server to a web browser when the user visits a site on a server. It is just a .txt file stored in a user’s computer. A cookie can be associated with one or more documents on the web server. More than one cookie can be associated with a document on the web server. Every cookie has a NAME-VALUE pair associated with it. Cookies have an expiration date associated with them.

 

Cookies are a plain text data record of 5 variable-length fields:

 

1.Expires − The date the cookie will expire. If this is blank, the cookie will expire when the visitor quits the browser.

2.Domain -The domain name of your site.

3. Path − The path to the directory or web page that set the cookie. This may be blank if you want to retrieve the cookie from any directory or page.

4.Secure − If this field contains the word “secure”, then the cookie may only be retrieved with a secure server. If this field is blank, no such restriction exists.

5. Name-Value – Cookies are set and retrieved in the form of key-value pairs.

     Create Cookies

 

We can create a cookie by assigning a string value to the document.cookie object.document.cookie = “key1=value1;key2=value2;expires=date”;

 

Store Cookies

 

Example

 

<html>

<head>

<script type=”text/javascript”>

function WriteCookie()

{

if( document.myform.customer.value == “” )

{

alert(“Enter some value!”);

return;

}

cookievalue= escape(document.myform.customer.value) + “;”; document.cookie=”name=” + cookievalue;

document.write (“Setting Cookies : ” + “name=” + cookievalue );

}

</script>

</head>

<body>

<form name=”myform” action=””>

Enter name: <input type=”text” name=”customer”/>

<input type=”button” value=”Set Cookie” onclick=”WriteCookie();”/> </form>

</body>

</html>

 

The example shows how a cookie can be created and stored. It retrieves the value from the textfield and stores it as a cookie.

<html>

<head>

<script type=”text/javascript”>

function ReadCookie()

{

var allcookies = document.cookie;

document.write (“All Cookies : ” + allcookies );

  • // Get all the cookies pairs in an array cookiearray = allcookies.split(‘;’);
  • // Now take key value pair out of this array for(var i=0; i<cookiearray.length; i++)

{

name = cookiearray[i].split(‘=’)[0]; value = cookiearray[i].split(‘=’)[1];

document.write (“Key is : ” + name + ” and Value is : ” + value);

}

}

 

The function ReadCookie() retrieve the stored cookie from document.cookie and store in a variable.Then we can use a for loop to read each cookie as a key-value pair.

 

Summary

 

This module explains about the JavaScript Event handling mechanisms. This module also explores about working with HTML form validation using HTML DOM and Event handling and finally discusses about JavaScript Cookies.

 

Web Links

  • http://www.w3schools.com/
  • www.doc.ic.ac.uk/~rcheung/teaching/2720/ppt/lecture04c.ppt
  • Paul J. Deitel, Harvey M. Deitel, Abbey Deitel, “Internet and World Wide Web How To Program”, 5th Edition, Pearson Education, 2012.