Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
10 views

JavaScript Events

The document explains JavaScript events and event handling in HTML, detailing various mouse, keyboard, form, and window/document events along with their corresponding event handlers. It provides examples of how to implement these events using JavaScript, including form validation techniques for both client-side and server-side validation. Additionally, it discusses the importance of combining both validation methods to enhance user experience and security.

Uploaded by

suryasahoo396
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

JavaScript Events

The document explains JavaScript events and event handling in HTML, detailing various mouse, keyboard, form, and window/document events along with their corresponding event handlers. It provides examples of how to implement these events using JavaScript, including form validation techniques for both client-side and server-side validation. Additionally, it discusses the importance of combining both validation methods to enhance user experience and security.

Uploaded by

suryasahoo396
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

JavaScript Events

The change in the state of an object is known as an Event. In html, there are various events which
represents that some activity is performed by the user or by the browser. When javascript code is
included in HTML, js react over these events and allow the execution. This process of reacting over the
events is called Event Handling. Thus, js handles the HTML events via Event Handlers.

For example, when a user clicks over the browser, add js code, which will execute the task to be
performed on the event.

Some of the HTML events and their event handlers are:

Mouse events:
Event Performed Event Handler Description

Click onclick When mouse click on an element

mouseover onmouseover When the cursor of the mouse comes over the element

Mouseout onmouseout When the cursor of the mouse leaves an element

mousedown onmousedown When the mouse button is pressed over the element

Mouseup onmouseup When the mouse button is released over the element

mousemove onmousemove When the mouse movement takes place.

Keyboard events:
Event Performed Event Handler Description

Keydown&Keyup onkeydown&onkeyup When the user press and then release the key

Form events:
Event Performed Event Handler Description

Focus onfocus When the user focuses on an element

Event Handling Notes Page 1


Submit onsubmit When the user submits the form

Blur onblur When the focus is away from a form element

Change onchange When the user modifies or changes the value of a form element

Window/Document events
Event Performed Event Handler Description

Load onload When the browser finishes the loading of the page

Unload onunload When the visitor leaves the current webpage, the browser unloads it

Resize onresize When the visitor resizes the window of the browser

Let's discuss some examples over events and their handlers.

Click Event with button


1. <html>
2. <head> Javascript Events </head>
3. <body>
4. <script language="Javascript" type="text/Javascript">
5.
6. function clickevent()
7. {
8. document.write("This is Javascriptt");
9. }
10.
11. </script>
12. <form>
13. <input type="button" onclick="clickevent()" value="Who's this?"/>
14. </form>
15. </body>
16. </html>

Event Handling Notes Page 2


Click Event with anchor tag
<html>
<head>
<title>
DHTML with JavaScript
</title>
<script type="text/javascript">
function dateandtime()
{
alert(Date());
}
</script>
</head>
<body bgcolor="orange">
<font size="4" color="blue">
<center> <p>
Click here # <a href="#" onClick="dateandtime();"> Date and Time </a>
# to check the today's date and time.
</p> </center>
</font>
</body>
</html>

Example 1: This example checks the Grade of a student according to the percentage criteria with the JavaScript and
HTML DOM. In this example, we type the code of a JavaScript in the <body> tag.

<html>
<head>
<title> Check Student Grade
</title>
</head>

<body>
<p>Enter the percentage of a Student:</p>
<input type="text" id="percentage">
<button type="button" onclick="checkGrade()">
Find Grade
</button>
<p id="demo"></p>
<script type="text/javascript">
function checkGrade() {
var x,p, text;

Event Handling Notes Page 3


p = document.getElementById("percentage").value;
x=parseInt(p);
if (x>90 && x <= 100) {
document.getElementById("demo").innerHTML = "A1";
} else if (x>80 && x <= 90) {
document.getElementById("demo").innerHTML = "A2";
} else if (x>70 && x <= 80) {
document.getElementById("demo").innerHTML = "A3";
}
else
document.getElementById("demo").innerHTML = "A4";
}
</script>
</body>
</html>
EXAMPLE

<html>
<p>
<p onmouseover="document.bgColor='greem'">Bright Green</p><br>
<p onmouseover="document.bgColor='red'">Red</p><br>
<p onmouseover="document.bgColor='magenta'">Magenta</p><br>
<p onmouseover="document.bgColor='purple'">Purple</p><br>
<p onmouseover="document.bgColor='blue'">Blue</p><br>
<p onmouseover="document.bgColor='yellow'">Yellow</p><br>
<p onmouseover="document.bgColor='black'">Black</p><br>
<p onmouseover="document.bgColor='orange'">Orange</p><br>
</p>
</html>

Example 0: The following example changes the color of a text.(Function with arguments)

<html>
<head>
<title>
getElementById.style.property example
</title>
</head>
<body>
<p id="demo"> This text changes color when click on the following different buttons. </p>
<input type="button" value="green" onclick="change_Color('green');">
<input type="button" value="blue" onclick="change_Color('blue');">
<script type="text/javascript">

Event Handling Notes Page 4


function change_Color(newColor) {
var element = document.getElementById('demo').style.color = newColor;
}
</script>
</body>
</html>

Example 1: The following example uses the DHTML CSS for changing the style of current element(this keyword)

<html>
<head>
<title>
Changes current HTML element
</title>
</head>
<body>
<center>
<h1 onclick="this.style.color='blue'"> This is a JavaTpoint Site </h1>
<center>
</body>
</html>

Example 2: This example uses the onclick event handler, which is used to change the text after clicking.

<html>
<head>
<title>
Example of onclick event
</title>
<script type="text/javascript">
function ChangeText(ctext)
{
ctext.innerHTML=" Hi TRIDENT! ";
}
</script>
</head>
<body>
<font color="red"> Click on the Given text for changing it: <br>
</font>
<font color="blue">
<h1 onclick="ChangeText(this)"> Hello World! </h1>
</font>
</body> </html>

Event Handling Notes Page 5


OnMouseOver Event Handler in JavaScript:

<html>
<script>
function over(){
var ele = document.getElementById('btn1');
ele.style.background='red';
ele.style.color='white';
}
function out(){
var ele = document.getElementById('btn1');
ele.style.background='Green';
ele.style.color='black';
}

</script>
<body> Demonstrating onmouseover based on DOM object</br>

<input type="button" id="btn1" value="Submit Button" onmouseover="over()"


onmouseout="out()" />

</body>
</html>

Focus Event
<html>
<head> Javascript Events</head>
<body>
<h2> Enter something here</h2>
<input type="text" id="input1" onfocus="focusevent()"/>
<script>

function focusevent()
{
document.getElementById("input1").style.background=" aqua";
}

</script>
</body>
</html>

Keydown Event
<script>
function press(){
var ele = document.getElementById('input');
ele.style.background='red';
ele.style.color='white';

Event Handling Notes Page 6


}
function up(){
var ele = document.getElementById('input');
ele.style.background='green';
ele.style.color='black';
}

</script>
<body> Demonstrating onkeyup based on DOM object</br>
<input type="text" value=”welcome” id="input" onkeydown="press()"
onkeyup="up()"/>
</body>

Load event
1. <html>
2. <head>Javascript Events</head>
3. </br>
4. <body onload="window.alert('Page successfully loaded');">
5. <script>
6.
7. document.write("The page is loaded successfully");
8.
9. </script>
10. </body>
11. </html>

FORM VALIDATION:

When we create forms, providing form validation is useful to ensure that your customers enter valid
and complete data. For example, you may want to ensure that someone inserts a valid e-mail
address into a text box, or perhaps you want to ensure that someone fills in certainfields.

We can provide custom validation for your forms in two ways: server-side validation and client-side
validation.

SERVER-SIDE VALIDATION

In the server-side validation, information is being sent to the server and validated using one of server-
side languages. If the validation fails, the response is then sent back to the client, page that contains
the web form is refreshed and a feedback is shown. This method is secure because it will work
even if JavaScript is turned off in the browser and it can‘t be easily bypassed by malicious users. On
the other hand, users will have to fill in the information without getting a response until they submit
the form. This results in a slow response from theserver.

The exception is validation using Ajax. Ajax calls to the server can validate as you type and provide
immediate feedback. Validation in this context refers to validating rules such as username availability.

Event Handling Notes Page 7


Server side validation is performed by a web server, after input has been sent to the server.

CLIENT-SIDE VALIDATION

Server-side validation is enough to have a successful and secure form validation. For better user
experience, however, you might consider using client-side validation. This type of validation is
done on the client using script languages such as JavaScript. By using script languages user‘s input
can be validated as they type. This means a more responsive, visually richvalidation.

With client-side validation, form never gets submitted if validation fails. Validation is being handled in
JavaScript methods that you create (or within frameworks/plugins) and users get immediate feedback
if validation fails.

Main drawback of client-side validation is that it relies on JavaScript. If users turn JavaScript off,
they can easily bypass the validation. This is why validation should always be
implementedonboththeclient and server. By combining server-side and client-side methods we can get
the best of the two: fast response, more secure validation and better userexperience.

Client side validation is performed by a web browser, before input is sent to a webserver.

Validation can be defined by many different methods, and deployed in many different ways.

Simple Example:

<html>

<head>

<title>Form Validation</title>

<script>

// Form validation code will come here.

function val()

var n = document.myForm.Name.value;

if( n == "" || (!isNaN(n)) || n.length< 3 || n.length>= 8)

alert( "Please enter valid name and minimum length 3 characters and maximum length 8 characters !" );

document.myForm.Name.focus();

return false;

Event Handling Notes Page 8


var emailID= document.myForm.EMail.value;

if( emailID=="")

alert( "Please provide your Email!" );

document.myForm.EMail.focus() ;

return false;

atposition = emailID.indexOf("@");

dotposition = emailID.lastIndexOf(".");

if (atposition<1 || dotposition<atposition+2 || dotposition+2>=emailID.length)

alert("Please enter a valid e-mail address \n atpostion:"+atposition+"\n dotposition:"+dotposition);

document.myForm.EMail.focus() ;

return false;

var z = document.myForm.Zip.value;

if(z =="" ||isNaN(z) || z.length!=6 )

alert( "Please provide a zip in the format #####." );

document.myForm.Zip.focus() ;

return false;

var c=document.myForm.Country.value;

if( c=="-1" )

Event Handling Notes Page 9


alert( "Please provide your country!" );

return false;

return( true );

</script>

</head>

<body bgcolor="bisque">

<h1><p align="center"><b>Application Form Validation Using JavaScript</b></p></h1>

<form name="myForm">

<table cellspacing="5" cellpadding="5" align="center" border="5" width="438">

<tr>

<td align="right"><b>Name</b></td>

<td><input type="text" name="Name" size="50" /></td>

</tr>

<tr>

<td align="right"><b>EMail</b></td>

<td><input type="text" name="EMail" size="50" /></td>

</tr>

<tr>

<td align="right"><b>Zip Code</b></td>

<td><input type="text" name="Zip" size="50" /></td>

</tr>

<tr>

<td align="right"><b>Country</b></td>

Event Handling Notes Page 10


<td>

<select name="Country">

<option value="-1" selected>[choose yours]</option>

<option value="1">INDIA</option>

<option value="2">UK</option>

<option value="3">USA</option>

</select>

</td>

</tr>

<tr>

<td align="right"></td>

<td><input type="button" value="Submit" onclick="val();"/></td>

</tr>

</font></table></form></body> </html>

JavaScript email validation


We can validate the email by the help of JavaScript.

There are many criteria that need to be follow to validate the email id such as:

o email id must contain the @ and . character


o There must be at least one character before and after the @.
o There must be at least two characters after . (dot).

1. <script>
2. function validateemail()
3. {
4. var x=document.myform.email.value;
5. var atposition=x.indexOf("@");

Event Handling Notes Page 11


6. var dotposition=x.lastIndexOf(".");
7. if (atposition<1 || dotposition<atposition+2 || dotposition+2>=x.length){
8. alert("Please enter a valid e-
mail address \n atpostion:"+atposition+"\n dotposition:"+dotposition);
9. return false;
10. }
11. }
12. </script>

Event Handling Notes Page 12

You might also like