0% found this document useful (0 votes)
4 views25 pages

JavaScript events

Uploaded by

yogitas804
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
4 views25 pages

JavaScript events

Uploaded by

yogitas804
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 25

JavaScript - Mouse Events

JavaScript mouse events allow users to control and interact with web
pages using their mouse. These events trigger specific functions or
actions in response to user clicks, scrolls, drags, and other mouse
movements.

To handle mouse events in JavaScript, you can use the


addEventListener() method. The addEventListener() method takes
two arguments: the event type and the event handler function. The
event type is the name of the event that you want to handle, and
the event handler function is the function that will be called when
the event occurs.

In web development, JavaScript provides a powerful mechanism to


respond to user interactions with the mouse through a set of events.
These events enable developers to create dynamic and interactive
web applications by capturing and handling various mouse-related
actions.

Common Mouse Events

Following are the most common JavaScript mouse events:

Mouse
Description
Event

When an element experiences the press of a mouse button, it triggers the


Click
click event.

Double Click The dblclick event fires upon the rapid double-clicking of a mouse button.

Mouse
The initiation of a mouse click triggers the 'mousedown' event, while the
Down and
completion of that click causes the 'mouseup' event to occur.
Mouse Up

Mouse When the mouse pointer moves over an element, it triggers the 'mousemove'
Move event; this event supplies developers with positional information about the
mouse. This data empowers them to devise responsive interfaces that are
rooted in dynamic mouse movements.

When the user attempts to open the context menu, typically by right-clicking,
Context
they trigger the contextmenu event. This event allows developers to
Menu
customize or inhibit default behaviour of the context menu.

When the mouse wheel rotates, it fires the 'wheel event'; this particular event
Wheel
commonly manifests in implementing features, notably zooming or scrolling.

Events like dragstart, dragend, dragover, dragenter, dragleave, and drop are
Drag and
associated with drag-and-drop functionality. They allow developers to create
Drop
interactive interfaces for dragging elements within a web page.

Example : Click Event

In this example we demonstrate the click event. When the button is


clicked, it prints an appropriate message to the console message i.e.
“Clicked!”. This event is often used while submitting forms.

<!DOCTYPE html>
<html>
<head>
<title>Click Event Example</title>
</head>
<body>
<button id="clickButton">Click me!</button>
<p id = "output"></p>
<script>
const clickButton = document.getElementById('clickButton');
const outputDiv = document.getElementById("output");
clickButton.addEventListener('click', function(event) {
outputDiv.innerHTML += 'Clicked!'+ JSON.stringify(event) +
"<br>";
});
</script>
</body>
</html>

Example: Double Click Event

The dblclick event operates in this example, triggering upon a


double-click of the designated button. We attach the event listener
to an element with "doubleClickButton" as its id. A user's double-
click on the button prompts a function that logs a console message,
confirming their interaction with it.

<!DOCTYPE html>
<html>
<head>
<title>Double Click Event Example</title>
</head>
<body>
<button id="doubleClickButton">Double-click me!</button>
<p id = "output"></p>
<script>
const doubleClickButton =
document.getElementById('doubleClickButton');
const outputDiv = document.getElementById("output");
doubleClickButton.addEventListener('dblclick', function(event) {
outputDiv.innerHTML += 'Double-clicked!' +
JSON.stringify(event) + "<br>";
});
</script>
</body>
</html>

Example: Mouse Down and Mouse Up Events

The use of the mousedown and mouseup events is exemplified in


this scenario: both events apply to a <div> element identified as
"mouseUpDownDiv." Two distinct event listeners are established;
one responds to the down action of the mouse button, while another
reacts upon release or up motion of said button. Upon pressing over
the designated div (mousedown), a message indicating that the user
has depressed their mouse button appears within your console log.
When the user releases the mouse button (mouseup), we also log
another message to indicate that the mouse button is up.

<!DOCTYPE html>
<html>
<head>
<title>Mouse Down and Mouse Up Events Example</title>
</head>
<body>
<div id="mouseUpDownDiv"
style="width: 600px; height: 100px; background-color:
lightblue;">
Please perform mouse down and up event any where in this DIV.
</div>
<p id = "output"></p>
<script>
const mouseUpDownDiv =
document.getElementById('mouseUpDownDiv');
const outputDiv = document.getElementById("output");
mouseUpDownDiv.addEventListener('mousedown',
function(event) {
outputDiv.innerHTML += 'Mouse button down!' +
JSON.stringify(event) + "<br>";
});

mouseUpDownDiv.addEventListener('mouseup', function(event)
{
outputDiv.innerHTML += 'Mouse button up!' +
JSON.stringify(event) + "<br>";
});
</script>
</body>
</html>
Example: Mouse Move Event

In this instance, we employ the mousemove event to monitor the


mouse pointer's movement over a specific <div> element identified
as "mouseMoveDiv." The handler function extracts clientX and
clientY properties from an event object that represents X-Y
coordinates of said pointer. Subsequently, these are logged into
console; thus offering real-time feedback on where exactly within
our designated div area is the user positioning their cursor.

<!DOCTYPE html>
<html>
<head>
<title>Mouse Move Event Example</title>
</head>
<body>
<div id="mouseMoveDiv"
style="width: 600px; height: 200px; background-color:
lightgreen;">
Please move you mouse inside this DIV.</div>
<p id = "output"></p>
<script>
const mouseMoveDiv =
document.getElementById('mouseMoveDiv');
const outputDiv = document.getElementById("output");
mouseMoveDiv.addEventListener('mousemove', function(event)
{
const x = event.clientX;
const y = event.clientY;
outputDiv.innerHTML += `Mouse moved to (${x}, ${y})` +
JSON.stringify(event) + "<br>";
});
</script>
</body>
</html>
Example: Wheel Event

This example showcases the wheel event, activated when the


mouse wheel is rotated. The event listener is attached to a <div>
element with the id "wheelDiv." When the user rotates the mouse
wheel over this div, the associated function logs a message to the
console, indicating that the mouse wheel has been rotated.

<!DOCTYPE html>
<html>
<head>
<title>Wheel Event Example</title>
</head>
<body>
<div id="wheelDiv"
style="width: 600px; height: 200px; background-color:
palevioletred;">
Please bring the curser inside this DIV and rotate the wheel of
mouse.</div>
<p id = "output"></p>
<script>
const wheelDiv = document.getElementById('wheelDiv');
const outputDiv = document.getElementById("output");
wheelDiv.addEventListener('wheel', function(event) {
outputDiv.innerHTML += 'Mouse wheel rotated!'+ event +
"<br>";
});
</script>
</body>
</html>
JavaScript - Keyboard Events

The keyboard events in JavaScript provide a way to interact with a


web page or application based on the user's keyboard input. These
events allow developers to capture and respond to various keyboard
actions, such as key presses, key releases, and character inputs.
The primary keyboard events in JavaScript include keydown,
keypress, and keyup.

Common Keyboard Events


 Keydown Event − When a key on the keyboard is pressed
down, it triggers the keydown event. This event equips
developers with information about the specific key that was
pressed: this includes its code and an indicator of whether
certain modifier keys such as Shift, Ctrl, or Alt were also
depressed.
 Keypress Event − The keypress event triggers when a user
types an actual character. Non-character keys, such as Shift or
Ctrl, do not activate this event. Developers frequently utilize it
to capture user input for form fields or create interactive typing
features.
 Keyup Event − Upon the release of a previously pressed key,
the system initiates the firing of a keyup event; this particular
event proves beneficial in tracking specific keys' releases and
subsequently implementing actions, thereby creating an
interactive user experience.

Example: Keydown Event

This example illustrates the application of JavaScript's keydown


event. The event listener seizes the keydown event upon pressing
any key, displaying in an HTML element identified as "output" - its
corresponding key (an event property).

<!DOCTYPE html>
<html>
<body>
<h3>Press any key</h3>
<script>
document.addEventListener('keydown', function (event) {
document.getElementById('output').innerHTML =
"Key pressed: " + event.key;
});
</script>
<div id="output"></div>
</body>
</html>

Example: Keypress Event

In this example, the keypress event is utilized to capture a typed


character. When a character is typed, the event listener triggers,
and the character is displayed in the HTML element with the id
"output".

<!DOCTYPE html>
<html>
<body>
<h3>Type a character</h3>
<div id="output"></div>
<script>
document.addEventListener('keypress', function (event) {
document.getElementById('output').innerHTML =
"Character pressed: " + event.key;
});
</script>
</body>
</html>

Example: Keyup Event

The keyup event is showcased in this example. It captures the event


when a key is released after being pressed. The released key is then
displayed on screen.
<!DOCTYPE html>
<html>
<body>
<h3>Press and Release a key</h3>
<div id="output"></div>
<script>
document.addEventListener('keyup', function (event) {
document.getElementById('output').innerHTML =
"Key released: " + event.key;
});
</script>
</body>
</html>

There is a difference between keydown and keypress. keydown is


triggered when any key is pressed down, providing information
about the pressed key, including modifiers. keypress is triggered
specifically when a character key is pressed, providing information
about the typed character without details on modifiers. Keydown
fires continuously as long as the key is held down.

In all the above examples, we have used the addEventListener but


these events can be listened to without this function as well. This is
because of you can assign event handlers directly to specific
properties. However, keep in mind that using addEventListener is
generally considered a better practice because it allows you to
attach multiple event handlers to the same event, and it separates
JavaScript logic from the HTML structure.

Example: Without using addEventListener method

In this example, we have an input box. When it detects a keydown


event (onkeydown), the handleKeyDown function is called and when
it detects a keyup event (onkeyup) it calls the handleKeyUp
function. Both the functions print appropriate messages to the
screen.

<!DOCTYPE html>
<html>
<body>
<div>Enter some text:
<input onkeydown="handleKeyDown(event)"
onkeyup="handleKeyUp(event)">
</div>
<div id="output"></div>
<script>
function handleKeyDown(event) {
document.getElementById('output').innerHTML+=
"Key pressed: " + event.key+'<br>Key code: ' +
event.keyCode+'<br>';
}
function handleKeyUp(event) {
document.getElementById('output').innerHTML+=
"Key released: ' + event.key+'<br><br>";
}
</script>
</body>
</html>
JavaScript - Form Events
Form Events

The form events in JavaScript are events that are associated with
HTML forms. These events are triggered by user actions when
interacting with form elements like text fields, buttons, checkboxes,
etc. Form events allow you to execute JavaScript code in response
to these actions, enabling you to validate form data, perform actions
on form submission or reset, and enhance the user experience.

JavaScript form events are hooked onto the elements in the


Document Object Model also known as DOM where by default the
bubbling propagation is used i.e. from bottom (children) to
top(parent).

List of Common Form Events

Here are some common form events:

Form
Description
Event

Triggered when a form is submitted. It's often used for form validation before
onsubmit
data is sent to the server.

Triggered when the form is reset, allowing you to perform actions when the
onreset
user resets the form.

Triggered when the value of a form element (input, select, textarea) changes.
onchange
Commonly used for user input validation or dynamic updates.

Triggered immediately when the value of an input element changes, allowing


oninput
for real-time handling of user input.

Triggered when an element receives focus, such as when a user clicks or tabs
onfocus into an input field. Useful for providing feedback or enhancing the user
experience.
Triggered when an element loses focus, such as when a user clicks outside an
onblur input field or tabs away. Useful for validation or updates triggered by loss of
focus.

Examples

Example: The onchange Event

The provided instance below illustrates the functionality of the


onchange event. This event activates upon a user's alteration in
dropdown (<select>) option selection. The function, handleChange,
dynamically modifies an <h2> element to display the newly
selected country; thus offering immediate feedback as user
preferences evolve.

<!DOCTYPE html>
<html>
<body>
<label for="country">Select a country:</label>
<select id="country" onchange="handleChange()">
<option value="USA">USA</option>
<option value="Canada">Canada</option>
<option value="UK">UK</option>
<option value="India">India</option>
</select>
<p id="txt"></p>
<script>
function handleChange() {
// Perform actions when the dropdown selection changes
var selectedCountry =
document.getElementById('country').value;
document.getElementById("txt").textContent=
"Selected country: "+selectedCountry;
}
</script>
</body>
</html>
Example: The onsubmit Event

The following example highlights the onsubmit event's functionality


upon form submission. The form features a username field and
password field; both must be filled for successful validation when
invoking the validateForm function. Upon passing this validation,
submitting the form will trigger display of a confirmation message.

<!DOCTYPE html>
<html>
<body>
<form onsubmit="return validateForm()">
<label for="username">Username:</label>
<input type="text" id="username" name="username"
required>
<label for="password">Password:</label>
<input type="password" id="password" name="password"
required>
<br/>
<input type="submit" value="Submit">
</form>
<script>
function validateForm() {
var username = document.getElementById('username').value;
var password = document.getElementById('password').value;
// Perform validation
if (username === "" || password === "") {
alert("Please fill in all fields");
return false; // Prevent form submission
}
alert("Form submitted! Username is:"+username+",Password
is:"+password);
return true; // Allow form submission
}
</script>
</body>
</html>

Example: The onreset event

In this demonstration, we observe the onreset event in action: it


triggers upon the user's click of the "Reset" button within a form.
The resetForm function once invoked, clears the form content filled
by user and then displays an alert to confirm successful reset of said
form.

<!DOCTYPE html>
<html>
<body>
<form onreset="resetForm()">
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<input type="reset" value="Reset">
</form>
<script>
function resetForm() {
// Perform actions when the form is reset
alert("Form has been reset!");
}
</script>
</body>
</html>

Example: The oninput Event

This example illustrates the oninput event: as the user types into
the search input field a real-time action, indeed! The handleInput
function triggers; it logs each current search input directly to screen.

<!DOCTYPE html>
<html>
<body>
<label for="search">Search:</label>
<input type="text" id="search" oninput="handleInput()">
<div id="message" style=" margin-top: 10px; font-weight:
lighter;border: 1px solid #ddd;padding: 10px; background-color:
#f9f9f9; border-radius: 5px; font-family: 'Arial', sans-serif; font-size:
14px; color: #333; width: 30%;"></div>

<script>
var messageElement = document.getElementById('message');
function handleInput() {
// Perform actions as the user types
var searchInput = document.getElementById('search').value;
messageElement.innerHTML+="Search input: " +
searchInput+'<br>';
}
</script>
</body>
</html>

Example: onfocus and onblur Events

The onfocus and onblur events merge in this example. The user's
focus on the input field triggers a call to the handleFocus function,
which then logs a message into the console. In contrast, when clicks
outside of or tabs away from said input field – this action triggers
execution of another function called handleBlur that subsequently
records an alternative message within that same console log.

<!DOCTYPE html>
<html>
<body>
<label for="name">Name:</label>
<input type="text" id="name" onfocus="handleFocus()"
onblur="handleBlur()">
<p id= "output"></p>
<script>
const output = document.getElementById('output');
function handleFocus() {
// Perform actions when the input gets focus
output.innerHTML += "Input has focus" + "<br>";
}
function handleBlur() {
// Perform actions when the input loses focus
output.innerHTML += "Input lost focus" + "<br>";
}
</script>
</body>
</html>
HTML DOM ClipboardEvent
The ClipboardEvent Object
The ClipboardEvent Object handles events that occur when the clipboard is
modified.

Clipboard Events
Event Occurs When

oncopy A user copies the content of an element

oncut A user cuts the content of an element

onpaste A user pastes content into an element

ClipboardEvent Properties
Property Returns

clipboardData An object containing the data affected by the clipboard operation


oncopy Event
Example
Call a function when copying some text of an <input> element:

<!DOCTYPE html>
<html>
<body>
<h1>HTML DOM Events</h1>
<h2>The oncopy Event</h2>

<input type="text" oncopy="myFunction()" value="Try to copy


me">

<p id="demo"></p>

<script>
function myFunction() {
document.getElementById("demo").innerHTML = "You copied
text!"
}
</script>

</body>
</html>
Description
The oncopy event occurs when the user starts a copy process in the browser.

The oncopy event occurs when the user copies element content (like a text
copy).

The oncopy event also occurs when the user copies a whole element (like an
image).

3 Ways to Copy:
 Press Ctrl + C
 Select "Copy" from the Edit menu in your browser
 Right click to display the context menu, and select "Copy"

Syntax
<!DOCTYPE html>
<html>
<body>
<h1>HTML DOM Events</h1>
<h2>The oncopy Event</h2>

<p>Assign an oncopy event to an input element.</p>

<input type="text" oncopy="myFunction()" value="Try to copy


me">

<p id="demo"></p>

<script>
function myFunction() {
document.getElementById("demo").innerHTML = "You copied
text!"
}
</script>

</body>
</html>

<!DOCTYPE html>
<html>
<body>
<h1>HTML DOM Events</h1>
<h2>The oncopy Event</h2>

<p>Use the HTML DOM to assign an oncopy event to an input


element.</p>

<input type="text" id="myInput" oncopy="myFunction()"


value="Try to copy me">

<p id="demo"></p>

<script>
document.getElementById("myInput").onpaste = function()
{myFunction()};
function myFunction() {
document.getElementById("demo").innerHTML = "You copied
text!"
}
</script>

</body>
</html>

<!DOCTYPE html>
<html>
<body>
<h1>HTML DOM Events</h1>
<h2>The oncopy Event</h2>

<p>Use the addEventListener() method to attach a copy event to


an input element.</p>

<input id="myInput" type="text" value="Try to copy me">

<p id="demo"></p>

<script>
document.getElementById("myInput").addEventListener("copy",
myFunction);
function myFunction() {
document.getElementById("demo").innerHTML = "You copied
text!"
}
</script>

</body>
</html>

oncut Event
Example
Call a function when cutting some text in an <input> element:

<!DOCTYPE html>
<html>
<body>
<h1>HTML DOM Events</h1>
<h2>The oncut Event</h2>

<input type="text" oncut="myFunction()" value="Try to cut this


text">

<p id="demo"></p>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "You cutted
text!";
}
</script>

</body>
</html>

Description
The oncut event occurs when the user cuts the content of an element.

The oncut event is mostly used on <input> elements with type="text".

Note
It is only possible to cut something from an input field.

It is not possible to cut the content of, for example a <p> element, UNLESS the
element has set contenteditable to "true" (See "More Examples" below).

3 Ways to Cut:
 Press Ctrl + X
 Select "Cut" from the Edit menu in your browser
 Right click to display the context menu, and select "Cut"

onpaste Event
Example
Call a function when pasting some text in an <input> element:

<!DOCTYPE html>
<html>
<body>
<h1>HTML DOM Events</h1>
<h2>The onpaste Event</h2>

<input type="text" onpaste="myFunction()" value="Paste


something here" size="40">

<p id="demo"></p>

<script>
function myFunction() {
document.getElementById("demo").innerHTML = "You pasted
text!";
}
</script>

</body>
</html>

Description
The onpaste event occurs when the user pastes some content into an
element.
The onpaste event is mostly used on <input> elements with type="text".

Note
It is only possible to paste something into an input field.

It is not possible to paste content into, for example a <p> element, UNLESS the
element has set contenteditable to "true" (See "More Examples" below).

3 Ways to Paste:
 Press Ctrl + V
 Select "Paste" from the Edit menu in your browser
 Right click to display the context menu, and select "Paste"

manan.chandrakar@gmail.com

You might also like