0% found this document useful (0 votes)
32 views

Unit 2

Uploaded by

Priyanka Reddy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views

Unit 2

Uploaded by

Priyanka Reddy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

UNIT- II

JavaScript programming of reactive web pages elements: JavaScript


Events - Mouse events, Keyboard events, Form events, window
events, Event handlers, Frames, Form object, JavaScript Form
Validation.
What is an Event?
Events are actions or occurrences that happen in the system
when some sort of interaction takes place on a web page.
A JavaScript event is something that happens when a user interacts
with the web page, such as clicking the button, resizing a window, or
entering text into a text area.
In some cases, the browser itself can trigger the events, such
as loading and unloading the pages.
• The basic purpose of JavaScript is to add interactivity to your
websites. This interactivity is provided by responding to user
actions.
1.Interactive events or simply events
2.Non-interactive events
1.Interactive events or Simple events: the set tasks user perform on
web page are called interactive events.
EX:1. When user click a button on web page, a click event
occurs. The button is called source of the event.
2. Moving mouse pointer on hyperlink. (Mouse Over event).
3. Submitting a form (submit event).
4. A keystroke (key press event).
2.Non interactive events: These events are not caused by user.
Ex: a load event occurs automatically every time a web page is
loaded in browser. The load event is associated with only the body
tag.
NOTE: An element is source of a specific set of events.

Event Handlers:
• Java script identifies an event and takes an action by executing
some piece of code. The procedure of taking action is called
Event handling.
• The specific JavaScript that takes the action is called Event
handler.
• Event handlers may be interactive or non-interactive. When an
event take place, java script identifies the event and execute its
handler.

The most common events that a web page finishes


loading, submitting a form, entering texts, clicking a link, or playing
and pausing a video.
The events are categorized mainly into four groups:
• Mouse events
• Keyboard events
• Form events
• Document/Window events
Mouse events:
• A Mouse Event gets triggered when the user interacts with a
mouse (pointing device) on the webpage, such as by clicking on
an element or moving the mouse over the element.
• The MouseEvent interface derives from the UIEvent interface,
which in turn derives from the Event interface.

The various types of mouse events are listed below:


The Click Event
• The click event gets fired when a mouse is both pressed and
released on a single element. Simply, we can say when the user
clicks on a button on the webpage, the click event is fired. We
can handle this event using an onclick event handler.
• Syntax: We can handle the click event either by using
the onclick event handler in HTML or Javascript and assigning a
JavaScript function to it or by using
JavaScript's addEventListener() method to attach the click event
to the HTML element.
• <element onclick="myFunction">
• object.onclick = function() { myFunction() };
• object.addEventListener("click", myFunction);

Program :
<!DOCTYPE html>
<html><head> <title>mouse events</title>
<script language="javascript">
function fun1()
{
alert("hai");
}
function fun2()
{
alert("bye");
}
</script>
</head>
<body>
<button onclick="fun1()">onClickme</button>
<button ondblclick="fun2()">ondblClickme</button>
</body>
</html>
Output :
Mouseover:
The mouseover is fires when the mouse comes over
the element.
Syntax:
• <element onmouseover ="myFunction">
• object.onmouseover = function() { myFunction() };
• object.addEventListener("mouseover", myFunction);

<html>
<head>
<h1> Javascript Events </h1>
</head>
<body>
<script >
function mouseoverevent()
{
alert("This is mouseover event");
}
</script>
<p onmouseover="mouseoverevent()"> Keep cursor over me</p>
</body>
</html>

Output:
Mouseout:
The mouseout event is fires when the mouse leaves an
element.
Syntax:
• <element onmouseout ="myFunction">
• object.onmouseout= function() { myFunction() };
• object.addEventListener("mouseout", myFunction);

Program:
<!DOCTYPE html>
<html>
<head>
<title>mouse events</title>
<script language="javascript">
function fun1()
{
alert("hai");
}
function fun2()
{
alert("bye");
}
</script>
</head>
<body>
<button onmouseOut="fun2()" >onClickme</button>
</body>
</html>
Output:

The Mousedown Event:


• The mousedown event gets fired when the user presses a mouse
button on an element. It differs from the click event as the click
event gets fired when the mouse button is pressed and released
while the pointer remains inside the same element.
• The mousedown event is triggered the moment the mouse
button is initially pressed. It enables you to distinguish between
the left, middle (scrolling wheel) and right mouse buttons.We
can handle this event using an onmousedown event handler.
• Syntax: We can handle the mousedown event either by using
the onmousedown event handler in HTML or Javascript and
assigning a JavaScript function to it or by using
JavaScript's addEventListener() method to attach the
mousedown event to the HTML element.
<element onmousedown="myFunction">
object.onmousedown = function(){myFunction()};
object.addEventListener("mousedown", myFunction);
The Mouseup Event:
• The mouseup event gets fired when the user releases the
mouse button over an element. If the user clicks outside an
element, drags the mouse onto it, and releases the button, it is
still counted as a mouseup event. This method is often used
together with the mousedown() method. We can handle this
event using an onmouseup event handler.
• Syntax: We can handle the mouseup event either by using
the onmouseup event handler in HTML or Javascript and
assigning a JavaScript function to it or by using
JavaScript's addEventListener() method to attach the mouseup
event to the HTML element.
• <element onmouseup="myFunction">
• object.onmouseup = function(){myFunction()};
• object.addEventListener("mouseup", myFunction);
Keyboard Events in JavaScript

Whenever a user interact with Keyboard, different events are fired.


There are three keyboard events, namely
1.keydown
2.keypress, and
3.keyup.
1. Keydown : Keydown happens when the key is pressed down,
and auto repeats if the key is pressed down for long.
2. Keypress : This event is fired when an alphabetic, numeric, or
punctuation key is pressed down.
3. Keyup: Keyup happens when the key is released.

• The onkeypress event is deprecated.


• It is not fired for all keys (like ALT, CTRL, SHIFT, ESC) in all
browsers.
• To detect if the user presses a key, always use
the onkeydown event. It works for all keys.
Keydown:
Keydown happens when the key is pressed down, and auto
repeats if the key is pressed down for long.

Syntax:
In HTML:
<element onkeydown="myScript">
In JavaScript:
object.onkeydown = function(){myScript};
In JavaScript, using the addEventListener() method:
object.addEventListener("keydown", myScript);
Program:
<!DOCTYPE html>
<html>
<body>
<input type="text" id="demo" onkeydown="myFunction()">
<script>
function myFunction()
{
document.getElementById("demo").style.backgroundColor = "red";
}
</script>
</body>
</html>
Program2:
<!DOCTYPE html><html>
<body>
<p>Press a key inside the text field to set a red background color.</p>
<input type="text" id="demo">
<script>
document.getElementById("demo").addEventListener("keydown",
myFunction);
function myFunction() {
document.getElementById("demo").style.backgroundColor = "red";
}</script></body></html>
Input Text value Property:
Syntax
• Return the value property:
textObject.value
• Set the value property:
textObject.value = text
Ex:
Name: <input type="text" id="fname" size="20"
name="fname"><br>
Age (from 1 to 100): <input type="text" id="age" size="20"
name="age"><br>
var age = document.getElementById("age").value;
var fname = document.getElementById("fname").value;

Keyup event:
Keyup happens when the key is released.
Syntax:
In HTML:
<element onkeyup="myScript">
In JavaScript:
object.onkeyup= function(){myScript};
In JavaScript, using the addEventListener() method:
object.addEventListener("keyup", myScript);
Program:
<!DOCTYPE html>
<html>
<body>
<h2>The keyup Event</h2>
<p>Assign an "onkeyup" event to an input element.</p>
Enter your name: <input type="text" id="fname"
onkeyup="myFunction()">
<script>
function myFunction() {
let x = document.getElementById("fname");
x.value = x.value.toLowerCase();
}
</script>
</body>
</html>

Keypress: This event is fired when an alphabetic, numeric, or


punctuation key is pressed down
Syntax:
In HTML:
<element onkeypress="myScript">
In JavaScript:
• object.onkeypress = function(){myScript};
In JavaScript, using the addEventListener() method:
• object.addEventListener("keypress", myScript);

Program:
<!DOCTYPE html>
<html>
<body>
Username:<input type="text" id="demo"
onkeypress="myFunction()">
<script>
function myFunction() {
alert("hello");
}
</script>
</body>
</html>
Form events:

Focus Event:
This event is fired when the user focuses on an element.
Program:
<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>
Blur Event: This event is fired when the focus is away from a form
element.
Program:
<html>
<body>
<p>When you enter the input field, a function is triggered which sets
the background color to yellow. When you leave the input field, a
function is triggered which sets the background color to red.</p>
Enter your name: <input type="text" id="myInput"
onfocus="focusFunction()" onblur="blurFunction()">
<script>
// Focus = Changes the background color of input to
yellow
function focusFunction()
{
document.getElementById("myInput").style.background =
"yellow";
}
// No focus = Changes the background color of input to red
function blurFunction()
{
document.getElementById("myInput").style.background =
"red";
}
</script>
</body>
</html>

Submit Event:
This event is fired when the user submits the form.
Program:
<html>
<body>
<p>When you submit the form, a function is triggered which alerts
some text.</p>
<form action="/action_page.php" onsubmit="myFunction()">
Enter name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
<script>
function myFunction()
{
alert("The form was submitted");
}
</script>
</body>
</html>
Change Event:
This event is fired when the user modifies or changes the value
of a form element.
Program:
<html>
<body>
<p>Modify the text in the input field, then click outside the field to
fire the onchange event.</p>
Enter some text:
<input type="text" name="txt" value="Hello"
onchange="myFunction(this.value)">
<script>
function myFunction(val)
{
alert("The input value has changed. The new value is: " + val);
}
</script>
</body>
</html>
Window Event :

Events triggered for the window object (applies to the <body>


tag):

Load
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction()
{
alert("Page is loaded");
}
</script>
</head>
<body onload="myFunction()">
<h1>Hello World!</h1>
</body></html>

<!DOCTYPE html>
<html>
<body onunload="myFunction()">
<h1>Welcome</h1>
<p>Close this window or press F5 to reload the page.</p>
<script>
function myFunction() {
alert("Thank you");
}
</script>
</body>
</html>
Resize:
<!DOCTYPE html>
<html>
<body onresize="myFunction()">
<p>Try to resize the browser window.</p>
<script>
function myFunction() {
alert("You have changed the size of the browser window!");
}
</script>
</body>
</html>
Error:
A function is triggered if an error occurs when loading the image. The
function shows an alert box with a text. In this example we refer to an
image that does not exist, therefore the onerror event occurs.
Program:
<!DOCTYPE html>
<html>
<body>
<img src="image.gif" onerror="myFunction()">
<script>
function myFunction() {
alert("The image could not be loaded.");
}
</script>
</body>
</html>
online and offline events:
Note:The ononline and onoffline events are only supported in Firefox
and Internet Explorer version 8 to 10.
Program:
<html>
<body ononline="onFunction()" onoffline="offFunction()">
<p>Open the File menu and click on "Work Offline" to toggle
between working online and offline. </p>
<script>
function onFunction()
{
alert ("Your browser is working online.");
}
function offFunction()
{
alert ("Your browser is working offline.");
}
</script>
</body>
</html>
afterprint:

<!DOCTYPE html>
<html>
<body onafterprint="myFunction()">
<h1>Try to print this document</h1>
<script>
function myFunction() {
alert("This document is now being printed");
}
</script>
</body>
</html>
beforeprint Event:

<!DOCTYPE html>
<html>
<body onbeforeprint="myFunction()">
<h1>Try to print this document</h1>
<script>
function myFunction() {
alert("You are about to print this document!");
}
</script>
</body>
</html>

Frames:
• Frames are used to divide your browser window into
multiple sections where each section can load a separate
HTML document.
• A collection of frames in the browser window is known
as a frameset.
• The window is divided into frames in a similar way the
tables are organized: into rows and columns.
Creating Frames:
• To use frames on a page we use <frameset> tag instead of
<body> tag.
• The <frameset> tag defines, how to divide the window into
frames.
• The rows attribute of <frameset> tag defines horizontal frames
and cols attribute defines vertical frames.
• Each frame is indicated by <frame> tag and it defines which
HTML document shall open into the frame.
Program:
<!DOCTYPE html>
<html>
<head>
<title>HTML Frames</title>
</head>
<frameset rows = "10%,80%,10%">
<frame name = "top" src = "top_frame.htm" />
<frame name = "main" src = "main_frame.htm" />
<frame name = "bottom" src = "bottom_frame.htm" />
</frameset>
</html>
Program2:
<!DOCTYPE html>
<html>
<head>
<title>HTML Frames</title>
</head>
<frameset cols = "25%,50%,25%">
<frame name = "left" src = "/html/top_frame.htm" />
<frame name = "center" src = "/html/main_frame.htm" />
<frame name = "right" src = "/html/bottom_frame.htm" />
</frameset>
</html>
Program:
<!DOCTYPE html>
<html>

<body>
<frameset cols="*,*,*">
<frame src="frame1.html">
<frame src="frame2.html">
<frame src="frame3.html">
</frameset>
</body>
</html>
Filename: Frame1.html
<!DOCTYPE html>
<html>
<body>
<h3>frame 1</h3>
<p> This content is in frame 1 </p>
</body>
</html>
Filename: Frame2.html
<!DOCTYPE html>
<html>
<body>
<h3>frame 2</h3>
<p> This content is in frame 2 </p>
</body>
</html>

Filename: Frame3.html
<!DOCTYPE html>
<html>
<body>
<h3>frame 3</h3>
<p> This content is in frame 3</p>
</body>
</html>

Forms:
Forms are the basics of HTML. We use HTML form
element in order to create the JavaScript form.
Form Object
• The Form object represents an HTML <form> element.
Access a Form Object
• You can access a <form> element by using getElementById():
Properties of Form Object:
▪ action
▪ elements[]
▪ encoding
▪ length
▪ method
▪ name
▪ target
▪ button
▪ checkbox
▪ FileUpload
▪ hidden
▪ password
▪ radio
▪ reset
▪ select
▪ submit
▪ text
▪ textarea
action:
action property of form object is used to access the action attribute
present in HTML associated with the tag.
This property is a read or writes property and its value is a string.
elements[]: elements property of form object is an array used to
access any element of the form.
It contains all fields and controls present in the form.
The user can access any element associated with the form by using
the looping concept on the elements array.
encoding:
The encoding property of a form object is used to access the
enctype attribute present in HTML associated with the tag.
This property is a read or write property and its value is a
string. This property helps determine the way of encoding the
form data.
length:
length property of form object is used to specify the number
of elements in the form. This denotes the length of the
elements array associated with the form.
method:
method property of form object is used to access the method
attribute present in HTML associated with the tag. This
property is a read or write property and its value is a string.
This property helps determine the method by which the form
is submitted.
name: name property of form object denotes the form name.
target: target property of form object is used to access the target
attribute present in HTML associated with the tag. This property
denotes the name of the target window to which form it is to be
submitted into
button: The button property of form object denotes the button GUI
control placed in the form. checkbox: checkbox property of form
object denotes the checkbox field placed in the form.
FileUpload: FileUpload property of form object denotes the file
upload field placed in the form.. hidden: The hidden property of form
object denotes the hidden field placed in the form.
password: password property of form object denotes the
object that is placed as a password field in the form.
radio: radio property of form object denotes the radio button
field placed in the form. reset: As the name implies, the reset
property of form object denotes the object placed as reset
button in the for.
select: select property of form object denotes the selection list
object placed in the form.
submit: submit property of form object denotes the submit
button field that is placed in the form.
text: text property of form object denotes the text field placed
in the form.
textarea: textarea property of form object denotes the text
area field placed in the form
Program:
<html>
<head>
<title> Login Form</title>
</head>
<body>
<h3> LOGIN </h3>
<form name ="Login_form" >
<h4> USERNAME</h4>
<input type="text" placeholder="Enter your email id"/>
<h4> PASSWORD</h4>
<input type="password" placeholder="Enter your password"/></b
r></br>
<input type="submit" value="Login” onsubmit="submit_form()"/>
<input type="button" value="SignUp" onClick="create()"/>
</form>
<script type="text/javascript">
function submit_form()
{
alert("Login successfully");
}
function create()
{
alert(“signUp");
}
</script>
</body>
</html>
JavaScript - Form Validation:
• Form validation normally used to occur at the server, after the
client had entered all the necessary data and then pressed the
Submit button.
• If the data entered by a client was incorrect or was simply
missing, the server would have to send all the data back to the
client and request that the form be resubmitted with correct
information. This was really a lengthy process which used to put
a lot of burden on the server.
• JavaScript provides a way to validate form's data on the client's
computer before sending it to the web server. Form validation
generally performs two functions.
Basic Validation − First of all, the form must be checked to
make sure all the mandatory fields are filled in. It would require just a
loop through each field in the form and check for data.
Data Format Validation − Secondly, the data that is entered
must be checked for correct form and value. Your code must include
appropriate logic to test correctness of data.
• It is important to validate the form submitted by the user
because it can have inappropriate values. So, validation is must
to authenticate user.
• JavaScript provides facility to validate the form on the client-
side so data processing will be faster than server-side validation.
Most of the web developers prefer JavaScript form validation.
• Through JavaScript, we can validate name, password, email,
date, mobile numbers and more fields.

JavaScript Form Validation Example:


• In this example, we are going to validate the name and
password. The name can’t be empty and password can’t be less
than 6 characters long.
• Here, we are validating the form on form submit. The user will
not be forwarded to the next page until given values are correct.
<html>
<head>
<script>
function validateform()
{
var name=document.myform.name.value;
var password=document.myform.password.value;

if (name==null || name=="")
{
alert("Name can't be blank");
return false;
}
else if(password.length<6)
{
alert("Password must be at least 6 characters long.");
return false;
}
}
</script>
<head>
<body>
<form name="myform" method="post" action="abc.jsp" onsub
mit="return validateform()" >
Name:
<input type="text" name="name"><br/>
Password:
<input type="password" name="password"><br/>
<input type="submit" value="register">
</form>
File: abc.html
<html>
<head>
<title>Valid User </title>
</head>
<body>
<h1>You are valid user</h1>
<p>Thanks for visiting our site</p>
</body>
</html>
JavaScript Retype Password Validation:

<script type="text/javascript">
function matchpass()
{
var firstpassword=document.f1.password.value;
var secondpassword=document.f1.password2.value;
If(firstpassword==secondpassword)
{
return true;
}
else
{
alert("password must be same!");
return false;
}
}
</script>
<form name="f1" action="register.html" onsubmit="return matchpa
ss()">
Password:
<input type="password" name="password" /><br/>
Re-enter Password:
<input type="password" name="password2"/><br/>
<input type="submit">
</form>
abc.html:
<html>
<head>
<title>Valid User </title>
</head>
<body>
<h1>You are valid user</h1>
<p>Thanks for visiting our site</p>
</body>
</html>

You might also like