0% found this document useful (0 votes)
3 views21 pages

Unit - 4. JavaScript Events and Objects (WD-II)

This document provides an overview of JavaScript events and objects, detailing various types of events such as mouse, keyboard, and form events. It explains how these events can be used to create interactive web applications, including examples of event handlers like onclick, onmouseover, and onkeydown. Additionally, it covers the syntax for implementing these events in HTML and JavaScript, along with practical use cases for each event type.

Uploaded by

pardheshubham562
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)
3 views21 pages

Unit - 4. JavaScript Events and Objects (WD-II)

This document provides an overview of JavaScript events and objects, detailing various types of events such as mouse, keyboard, and form events. It explains how these events can be used to create interactive web applications, including examples of event handlers like onclick, onmouseover, and onkeydown. Additionally, it covers the syntax for implementing these events in HTML and JavaScript, along with practical use cases for each event type.

Uploaded by

pardheshubham562
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

4.

JavaScript Events and Objects

Unit 4
JavaScript Events and Objects
JavaScritp Events:
Events in JS are actions that happen when a user interacts through the browser with
the help of an input field or other interactive elements available in the browser. Events are a
part of the Document Object Model (DOM) Level 3 and each HTML element includes a set
of events that can trigger the code in JS.
A JavaScript event helps us create interactive and dynamic web applications and web
pages.
Event Types
JavaScript supports a variety of event types. Common categories include:
• Mouse Events: click, dblclick, mousemove, mouseover, mouseout
• Keyboard Events: keydown, keypress, keyup
• Form Events: submit, change, focus, blur
• Window Events: load, resize, scroll
Mouse Events:
1. onClick Event:
The onclick event in JavaScript is used to execute a function when an HTML element is
clicked. It's a very common and useful event for creating interactive web pages.
The onclick event occurs when a user clicks on an element.
You can add onclick in:
• HTML directly (inline)
• JavaScript (DOM method)
Example:
<!DOCTYPE html>
<html>
<head>
<title>Onclick Event Example</title>
</head>
<body>
<h2>JavaScript onclick Event Example</h2>
<button onclick="showMessage()">Click Me</button>
<p id="output"></p>
<script>
function showMessage() {
[Link]("output").innerHTML = "You clicked the button!";
}
</script>
</body>
</html>
Output:

CA-125 Web Design-II


4. JavaScript Events and Objects

2. ondbclick:
The ondblclick event triggers when a user double-clicks (i.e., two rapid clicks) on an HTML
element. It’s useful for actions that should not be done by just a single click — like editing
content, zooming in, or expanding sections.
The onmouseover event attribute works when the mouse pointer moves over the specified
element. It is basically:
• Activated when the mouse pointer enters the designated HTML element.
• Enables executing JavaScript code when the mouse hovers over the element.
• Ideal for enhancing user experience by providing feedback or additional information.
Syntax
<element onmouseover = "script">
Example:
<!DOCTYPE html>
<html>
<head>
<title>ondblclick Example</title>
</head>
<body>
<h2 ondblclick="changeColor(this)">Double Click Me to Change Color</h2>
<script>
function changeColor(element) {
[Link] = "red";
}
</script>
</body>
</html>
Output:
Before double click After double click

[Link] Event:
The onmousedown event in JavaScript is triggered when the user presses a mouse button
down over an HTML element. It is commonly used in interactive web pages to perform
actions when a mouse button is pressed.
This event is part of the Mouse Events category, and it works with all standard mouse buttons
(left, middle, and right).
• The onmousedown event occurs before the onclick event.

CA-125 Web Design-II


4. JavaScript Events and Objects

• It is used to detect which mouse button was pressed and to start actions like dragging,
highlighting, or showing menus.
• It can be applied to any HTML element.
Mouse Button Codes
You can check which mouse button was pressed using the [Link] property:
• 0 = Left button
• 1 = Middle button (wheel)
• 2 = Right button

Syntax:
<element onmousedown="myFunction()">Content</element>
Example:
<html>
<head>
<title>onmousedown Example</title>
<script>
function showMessage(event) {
let message = "";
if ([Link] === 0) {
message = "Left mouse button pressed.";
} else if ([Link] === 1) {
message = "Middle mouse button pressed.";
} else if ([Link] === 2) {
message = "Right mouse button pressed.";
}
[Link]("output").innerText = message;
}
</script>
</head>
<body>
<h2 onmousedown="showMessage(event)">Click and Hold Your Mouse Here</h2>
<p id="output"></p>
</body>
</html>
Output:
When you press right key when you press left key when you press middle key

[Link] Event:

CA-125 Web Design-II


4. JavaScript Events and Objects

The onmouseenter event in JavaScript is triggered when the mouse pointer enters the area
of an HTML element. It is used to detect when the user moves the mouse over an element
without triggering again when moving over child elements (unlike onmouseover).
• onmouseenter is similar to onmouseover, but it does not bubble.
• It fires only once when the pointer enters the element—not repeatedly when moving
over inner elements.
• Commonly used for UI effects like tooltips, highlighting, menus, or animations.
Syntax:
<element onmouseenter="myFunction()">Content</element>
Example:
<html>
<head>
<title>onmouseenter Simple Example</title>
<script>
function showMessage() {
[Link]("message").innerText = "Mouse entered the box!";
}
</script>
</head>
<body>
<h2>Move your mouse over the box:</h2>
<div id="myBox" onmouseenter="showMessage()"
style="width:200px; height:100px; background-color:lightgray; border:1px solid
black;">
Hover here
</div>
<p id="message"></p>
</body>
</html>
Output:

5. onmouseleave Event:
The onmouseleave event is triggered when the mouse pointer leaves the area of an HTML
element. It is the opposite of onmouseenter.
• It is used to detect when the user's mouse exits an element.
• Useful for hiding tooltips, reversing styles, or stopping animations.

CA-125 Web Design-II


4. JavaScript Events and Objects

• Unlike onmouseout, onmouseleave does not fire when the mouse moves to a child
element—it only fires once when the mouse completely leaves the parent element.
Syntax:
<element onmouseleave="myFunction()">Content</element>
Example:
<html>
<head>
<title>onmouseleave Example</title>
<script>
function resetMessage() {
[Link]("message").innerText = "Mouse has left the box.";
}
</script>
</head>
<body>
<h2>Move your mouse out of the box:</h2>
<div id="myBox" onmouseleave="resetMessage()"
style="width:200px; height:100px; background-color:lightgreen; border:1px solid
black;">
Hover inside me, then move your mouse out
</div>
<p id="message"></p>
</body>
</html>
Output:

6. onmousemove Event:
The onmousemove event in JavaScript is triggered when the mouse pointer moves within an
HTML element. This event is commonly used to create interactive user interfaces, such as
tooltips, drag-and-drop features, games, or custom cursor effects.
• It is used to detect and respond to the movement of the mouse inside an element.
• Useful for tracking cursor position, creating interactive effects, updating
coordinates, or triggering live responses like color changes or animations.
• This event fires continuously as the mouse moves—not just once.
Syntax:
<element onmousemove="myFunction(event)">Content</element>
Example:

CA-125 Web Design-II


4. JavaScript Events and Objects

<html>
<head>
<title>onmousemove Example</title>
<script>
function showCoordinates(event) {
const x = [Link];
const y = [Link];
[Link]("output").innerText = "Mouse Position - X: " + x +
", Y: " + y;
}
</script>
</head>
<body>
<h2>Move your mouse inside the box:</h2>
<div id="myBox" onmousemove="showCoordinates(event)"
style="width:300px; height:150px; background-color:lightblue; border:1px solid
black;">
Move your mouse here
</div>
<p id="output"></p>
</body>
</html>
Output:

7. onmouseout Event:
The onmouseout event in JavaScript occurs when the mouse pointer leaves (moves out of)
the area of an HTML element.
This event is often used to reverse changes made when the mouse entered the element (with
onmouseover), such as removing highlight effects, hiding tooltips, or resetting styles.
Common Use Cases
• Changing the background color when the mouse leaves a button.
• Hiding a tooltip or a message when the pointer is no longer on an image or text.
• Reverting to original styling after hovering.
Syntax:
<element onmouseout="functionName()">Content</element>
Example:
<html>
<head>
<title>onmouseout Example</title>

CA-125 Web Design-II


4. JavaScript Events and Objects

<script>
function changeColorOut() {
[Link]("demo").[Link] = "white";
}
function changeColorIn() {
[Link]("demo").[Link] = "lightblue";
}
</script>
</head>
<body>
<h3 id="demo"
onmouseover="changeColorIn()"
onmouseout="changeColorOut()"
style="width: 300px; padding: 20px; border: 1px solid black;">
Hover over me with your mouse!
</h3>
</body>
</html>
Output:

8. onmouseover Event:
The onmouseover event in JavaScript occurs when the mouse pointer moves over (enters)
the area of an HTML element.
This event is typically used to:
• Highlight elements
• Display additional information (like tooltips)
• Animate buttons or menus on hover
It is commonly paired with the onmouseout event to reverse the effect.
Common Use Cases
• Changing text or background color on hover
• Showing a description or tooltip when hovering over an image
• Enlarging a button or icon when the user hovers over it
Syntax:
<element onmouseover="functionName()">Content</element>
Example:
<!DOCTYPE html>
<html>
<head>
<title>onmouseover Example</title>

CA-125 Web Design-II


4. JavaScript Events and Objects

<script>
function highlightText() {
[Link]("text").[Link] = "red";
}
</script>
</head>
<body>
<p id="text"
onmouseover="highlightText()"
style="font-size: 20px;">
Hover over this text to change its color!
</p>
</body>
</html>
Output:

9. onmouseup Event:
The onmouseup event in JavaScript occurs when the mouse button is released after being
pressed down over an HTML element.
This event is useful when you want to trigger an action after the user releases the mouse
button, such as submitting data, changing styles, or showing messages.
It often works together with onmousedown, which detects when the button is pressed down.
Common Use Cases
• Detecting mouse clicks (along with onmousedown)
• Creating custom buttons or controls
• Showing messages or animations after a mouse click is completed
Syntax:
[Link]("elementID").onmouseup = functionName;
Example:
<html>
<head>
<title>onmouseup Example</title>
<script>
function showMessage() {
alert("Mouse button released!");
}
</script>
</head>
<body>
<button onmouseup="showMessage()">
Click and Release Me

CA-125 Web Design-II


4. JavaScript Events and Objects

</button>
</body>
</html>
Output:

Key Events:
1. onkeydown Event:
The onkeydown event in JavaScript occurs when the user presses a key on the keyboard.
This event is triggered as soon as the key is pressed down, before it is released. It can be used
to detect user keystrokes and perform actions like shortcuts, form navigation, or custom key-
based controls.
This event is commonly used for:
• Detecting specific key presses (e.g., Enter, Escape)
• Creating keyboard shortcuts
• Real-time form input validation
• Game controls and interactive applications
Syntax:
• <input type="text" onkeydown="myFunction(event)">
• [Link]("keydown", myFunction);
Example:
<!DOCTYPE html>
<html>
<body>
<h3>Press any key in the textbox:</h3>
<input type="text" onkeydown="keyPressed(event)">
<script>
function keyPressed(event) {
alert("You pressed: " + [Link]);
}
</script>
</body>
</html>
Output:

CA-125 Web Design-II


4. JavaScript Events and Objects

2. onkepress Event:
The onkeypress event in JavaScript occurs when the user presses a key that produces a
character value. It is triggered after the key is pressed down but before the character
appears in the input field.
This event is typically used for:
• Capturing typed characters
• Allowing or restricting input (e.g., only numbers)
• Creating typing effects or shortcuts
Syntax:
• <input type="text" onkeypress="myFunction(event)">
• [Link]("keypress", myFunction);
Example:
<!DOCTYPE html>
<html>
<body>
<h3>Type a character:</h3>
<input type="text" onkeypress="showChar(event)">
<script>
function showChar(event) {
alert("You pressed: " + [Link]);
}
</script>
</body>
</html>
Output:
If the user presses a, an alert will show: "You pressed: a"
3. onkeyup Event:
The onkeyup event occurs when the user releases a key on the keyboard after pressing it.
It is triggered after both onkeydown and onkeypress (if applicable). This event is useful when
you want to perform an action after the user has finished typing a character or key.
Common uses:
• Real-time form validation
• Live search filtering
• Displaying typed text
• Detecting key releases
Syntax:
<input type="text" onkeyup="myFunction(event)">
Example:
<!DOCTYPE html>
<html>
<body>
<h3>Type something:</h3>
<input type="text" onkeyup="showText([Link])">

CA-125 Web Design-II


4. JavaScript Events and Objects

<p id="output"></p>
<script>
function showText(text) {
[Link]("output").innerText = "You typed: " + text;
}
</script>
</body>
</html>
Output:
As you type, it shows: You typed: hello (in real time).
onfocus,onload,onunload,onsubmit
onfocus():
<!DOCTYPE html>
<html>
<body>
Enter your name: <input type="text" onfocus="myFunction(this)">
<script>
function myFunction(x)
{
[Link] = "yellow";
}
</script>
</body>
</html>
onblur():
<!DOCTYPE html>
<html>
<body>
Enter your name: <input type="text" id="fname" onblur="myFunction()">
<script>
function myFunction()
var x = [Link]("fname");
xvalue=[Link]();
</script>
</body
</html>
Onload():
The onload event is triggered when a web page or a specific element (like an image) is
fully loaded in the browser.
It is most commonly used to:
• Run JavaScript after the page has finished loading
• Automatically start animations or scripts
• Show welcome messages or initialize form values

CA-125 Web Design-II


4. JavaScript Events and Objects

<!DOCTYPE html>
<html>
<body onload="welcomeUser()">
<script>
function welcomeUser() {
alert("Welcome to the website!");
}
</script>
</body>
</html>
Output: When the page finishes loading, an alert message says: "Welcome to the website!"

Onunload():
The onunload event is triggered when the user leaves the page, such as by:
• Closing the browser tab or window
• Refreshing the page
• Navigating to a different page
It is typically used to:
• Display exit confirmation (limited support in modern browsers)
• Save user data before leaving
• Perform cleanup tasks (e.g., disconnect from a server)
<!DOCTYPE html>
<html>
<body onunload="alert('Thanks for visiting!')">
<p>Close or refresh the tab to see the message.</p>
</body>
</html>

onSubmit() Events:
HTML has a form element tha

t is used to get the data from the user and send the data to the server.
Before the HTML form sends data to the server, it generates an event called "submit"
This event can be utilized to execute a JavaScript function that can either validate the form
data or notify the user of the form submission.
<!DOCTYPE html>
<html>
<body>
<form action="/action_page.php" onsubmit="myFunction()">
Enter name: <input type="text" name="fname">

CA-125 Web Design-II


4. JavaScript Events and Objects

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


</form>
<script>
function myFunction() {
alert("The form was submitted");
}
</script>
</body>
</html>
String Method

Math Object

CA-125 Web Design-II


4. JavaScript Events and Objects

• The Math object in JavaScript is a built-in object that provides mathematical


constants and functions.
It helps perform complex mathematical operations like rounding numbers, calculating
powers, generating random numbers, and more.
• The built-in Math object includes mathematical constants and functions. You do not
need to create the Math object before using it.
• JavaScript math object is a top-level, a predefined object for mathematical constants
and functions.
• Cannot be created by the user. It is a predefined object.
• Mathematical properties and functions can be calculated by [Link] or
[Link].
Methods
1. max(x,y)
The [Link]() method is used to get the maximum value among the arguments passed as an
array.
Here, we have passed six arguments to the [Link]() object, and the method returns the
maximum value from them.
Syntax:
[Link](value1, value2, ..., valueN);
Example:
<html>
<head>
<title> JavaScript - [Link]() method </title>
</head>
<body>
<p id = "output"> </p>
<script>
let ans = [Link](100, 10, -5, 89, 201, 300);
[Link]("output").innerHTML = ans;
</script>
</body>
</html>
Output:

2. min(x,y)
In JavaScript, the [Link]() method accepts any number of arguments, and it returns the
minimum value among those [Link] any of the arguments is not a number, "NaN"
(Not-a-Number) is returned. If there are no arguments, "Infinity" is returned, because there's
no minimum value to return.
Syntax:
[Link](value1, value2, ..., valueN);
Example:

CA-125 Web Design-II


4. JavaScript Events and Objects

<html>
<body>
<script> let number = [Link](-5, -15, -25, -55, -100);
[Link]("Lowest number: ", number);
</script>
</body>
</html>
Output:
-100
3. random()
The [Link]() method in JavaScript is used to generate a pseudo-random decimal
number between 0 (inclusive) and 1 (exclusive).
Note: The [Link]() is not suitable for cryptographic or security-related purposes. The
numbers generated by [Link]() are not truly random and should not be relied upon for
tasks that require high security standards. Instead use the Web Crypto API, and more
precisely the [Link]() method.
Syntax:
Example:
<html>
<body>
<script>
const result = [Link]();
[Link](result);
</script>
</body>
</html>
Output:
If we execute the above program, it gives a random number between 0 to 1.
Example2:
<html>
<body>
<script>
const result = [Link]([Link]() * 100);
[Link](result);
</script>
</body>
</html>
Output:
As we can see in the output, it generates random numbers from 0 to 99.
4. round(x)
The JavaScript [Link]() method accepts a numeric value as a parameter, round it to the
nearest integer and returns the result.
The [Link]() method works as follows −

CA-125 Web Design-II


4. JavaScript Events and Objects

• If the fractional portion of the number is less than 0.5, [Link]() returns the
greatest integer less than or equal to x.
• If the fractional portion of the number is 0.5 or greater, [Link]() returns the
smallest integer greater than or equal to x.
Syntax
[Link](x);
Example:
<html>
<body>
<script>
let value1 = [Link](5.49);
[Link](value1, "<br>");
let value2 = [Link](5.50);
[Link](value2, "<br>");
let value3 = [Link](5.99);
[Link](value3);
</script>
</body>
</html>
Output:
If we execute the above program, the specified positive integers got rounded to the nearest
integers.

5. pow()
The JavaScript [Link]() method is used to calculate the power of a base number raised to
an exponent. This method takes two arguments: the base (the number we want to raise) and
the exponent (the power to which we want to raise the base).
Following are the cases, where this method returns "NaN" as result −
• If the exponent is NaN.
• If the base is NaN and exponent is not 0.
• If the base is 1 and exponent is Infinity.
• If the base < 0 and exponent is not an integer.
• If either or both the arguments are non-numeric.
Syntax:
[Link](base, exponent);
Example:
<html>
<body>
<script>
let value1 = [Link](5, 3);
[Link](value1, "<br>");

CA-125 Web Design-II


4. JavaScript Events and Objects

let value2 = [Link](-5, -3);


[Link](value2);
</script>
</body>
</html>
Output:

Math Property:

Form Object
In JavaScript, the Form Object is used to represent an HTML <form> element. This object
allows developers to interact with form data, access form fields (like input, textarea, etc.), and
control form submission and validation.
The Form Object is part of the DOM (Document Object Model) and can be accessed using:
[Link].
Syntax:
Syntax:
• [Link][index]
• [Link]["formName"]
• [Link]("formID")

Form Object, Elements and properties :

CA-125 Web Design-II


4. JavaScript Events and Objects

Action:
Action property of form object is used to access the action attribute present in HTML
associated with the <form> tag.
Example
<form action="[Link]" method="post">
Method:
This property helps determine the methed by which the form is submitted.
The method attribute specifies how to send form-data.
There are two methods-GET and POST
GET Method-
• Form-data into the URL in name/value pairs.
• The length of a URL. is limited (about 3000 characters)
• Never use GET to send sensitive data! (will be visible in the URL)
• GET is better for non-secure data.
• Example <form action="[Link]" method="get">
POST Method -
• form-data inside the body of the HTTP request (data is not shown is in URL)
• Has no size limitations
• GET is better for secure data.
• Example <form action="[Link]" method="post">
Elements:
Elements property of form object is 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.
Text:
Text property of form object denotes the text field placed in the form.
Name:
Name property of form object denotes the form name.
Example -
Name: <input type="text" id="name" name="name" maxlength=10>
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.
Example-
Name: <input type="text" id="name" name="name" maxlength=10>
Password:
Password property of form object denotes the object that is placed as a password field in the
form.
Example:
<input type="password" id="pwd" name="pwd" minlength="8">
Hidden:
The hidden property of form object denotes the hidden field placed in the form. The <input
type="hidden"> defines a hidden input field.

CA-125 Web Design-II


4. JavaScript Events and Objects

Example:
<form action="[Link]" target="blank">
First name: <input type="text" id="fname" name="fname"><br><br>
<input type="hidden" id="custld" name="Mahesh" value="43015">
<input type="submit" value="Submit">
Text area:
Text area property of form object denotes the text area field placed in the form.
Example:
Address: <textarea id="tx1" name="add" rows="4" cols="50">
Target:
The target attribute specifies if the submitted result will open in a new browser tab, or in the
same / current tab.
There are two options - "_self" and "blank"
• _self - The default value is "_self" which means the form will be submitted in the
current window.
<form action="" target="_self">
• blank - To make the form result open in a new browser tab, use the value
"blank"
<form action="" target="_blank">
Checkbox:
Checkbox property of form object denotes the checkbox field placed in the form.
Example:
Hobbies: <br>
<input type="checkbox" name="hl" value="sports"> Sports <br>
<input type="checkbox" name="h2" value="music">Music<br>
<input type="checkbox" name="h3" value="movies">Movies<br>
Radio:
radio property of form object denotes the radio button field placed in the form.
Example:
<input type="radio" name="gender" value="male"> Male
<input type="radio" name=" gender" value="female"> Female
Select:
Select property of form object denotes the selection list object placed in the form.
Country:
<select id="country" name="country">
<option value="india">India</option>
<option value="usa">United States</option>
<option value="canada">Canada</option>
<option value="uk">United Kingdom</option>
</select><p></p>
FileUpload:
FileUpload property of form object denotes the file upload field placed in the form.
Example:

CA-125 Web Design-II


4. JavaScript Events and Objects

Select a file: <input type="file" id="myfile" name="myfile"><br><br>


<input type="submit">
Button:
The button property of form object denotes the button GUI control placed in the form.
Example:
<input type="submit" value="Submit">
<input type="reset" value="reset">
Reset:
As the name implies, the reset property of form object denotes the object placed as reset
button in the form.
Example:
<input type="reset" value="Reset">
Submit:
Submit property of form object denotes the submit button field that is placed in the form.
<input type="submit" value="Submit">

Program:
<!DOCTYPE html>
<html>
<body>
<h3>A demonstration of how to access a FORM element</h3>
<form id="myForm" action="[Link]">
First name: <input type="text" id="tb1" name="fname"><br>
Last name: <input type="text" id="tb2" name="Iname"><br>
<input type="submit" value="Submit">
</form>
<p>Click on "Show Data" button to show data</p>
<button onclick="myFunction()">Show Data</button>
<p id="demo"></p>
<p id="demo1"></p>
<script>
function myFunction()
{
var x = [Link]("myForm").elements[0].value;
[Link]("demo").innerHTML = "Your Name "+x;
var y = [Link]("myForm").elements[1].value;
[Link]("demo1").innerHTML = "Your Surname : " +y;
}
</script>
</body>
</html>
Output:

CA-125 Web Design-II


4. JavaScript Events and Objects

CA-125 Web Design-II

You might also like