JavaScript events
JavaScript 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.
Mouse
Description
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.
<!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>
<!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>
<!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
<!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
<!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
<!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>
<!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>
<!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.
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 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
<!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
<!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>
<!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>
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>
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
ClipboardEvent Properties
Property Returns
<!DOCTYPE html>
<html>
<body>
<h1>HTML DOM Events</h1>
<h2>The oncopy Event</h2>
<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 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 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 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>
<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.
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>
<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