DOM Events and Forms
By Syncfusion®, Inc. · Last updated
Attaching and removing event listeners, the everyday events from click to blur, and reading, updating and validating the controls in a form.
What Are Events and Forms?
Event = the browser's signal that something happened: a click, a key press, a form being sent. Event listener = code that waits for an event; its handler is the function it runs.
element.addEventListener("click", handler)connects them.- The handler receives an event object describing what happened.
- Forms collect what people enter; events say when to read it.
Simple lesson: tell an element which event to watch, and which function to call.
A Real-World Example
On a checkout page, typing in the coupon box updates a live counter (input).
Leaving the email box checks it (blur).
Pressing Place order or Enter runs one submit handler that checks the form and stops the page from reloading.
Add to cart
listener: "click" handler(event)
Cart: 1 → 2
The click rings the listener; the handler does the work.
Each box shows a live page, then its script triggers the event itself (for example with .click()) so the output appears. After it runs, use the page yourself: click, hover and type.
What You Will Learn
- Adding events, and the common event types.
- Mouse, keyboard,
change/input,submit,focus/blur. addEventListener()options andremoveEventListener().- Form elements: reaching, reading and updating controls.
- Validating forms, by hand and with the browser.
Events
Think of the listener as a doorbell and the handler as what you do when it rings.
Adding events
Three parts: an element, an event name, a function. Adding the listener only stores the function; it runs on the click.
One button, one click listener, one handler
<button id="greet" type="button">Say hello</button>
<p id="message">Nobody has clicked yet.</p>
<script>
const greet = document.querySelector("#greet");
const message = document.querySelector("#message");
greet.addEventListener("click", () => {
message.textContent = "Hello, Asha!";
console.log("The handler ran.");
});
console.log("Before the click:", message.textContent);
greet.click();
console.log("After the click:", message.textContent);
</script>
Expected output:
Before the click: Nobody has clicked yet.
The handler ran.
After the click: Hello, Asha!
Pass the function, not its result. addEventListener("click", showMessage) waits; showMessage() runs it once, straight away.
Click event
Press and release on an element (or Enter/Space on a focused button). A variable outside the handler remembers between clicks.
Counting clicks on an Add to cart button
<button id="add" type="button">Add to cart</button>
<p>Items in cart: <span id="count">0</span></p>
<script>
const add = document.querySelector("#add");
const count = document.querySelector("#count");
let items = 0;
add.addEventListener("click", () => {
items += 1;
count.textContent = String(items);
});
add.click();
add.click();
add.click();
console.log("Items after three clicks:", items);
</script>
Expected output:
Items after three clicks: 3
Double click event
dblclick: two quick clicks, often for "edit". No .dblclick() shortcut, so the script sends new MouseEvent("dblclick") with dispatchEvent().
Double-click a task to mark it as done
<p id="task">Pay the electricity bill</p>
<script>
const task = document.querySelector("#task");
task.addEventListener("dblclick", () => {
task.style.textDecoration = "line-through";
console.log("Marked as done:", task.textContent);
});
task.dispatchEvent(new MouseEvent("dblclick", { bubbles: true }));
console.log("Text decoration is now:", task.style.textDecoration);
</script>
Expected output:
Marked as done: Pay the electricity bill
Text decoration is now: line-through
A real double click also fires two click events first. Do not listen for both on one element.
Mouseover event
The pointer moves onto an element. Use it for hover actions that need code.
Show a hint when the pointer moves over a price
<p>Price: <span id="price">₹499</span></p>
<p id="hint"></p>
<script>
const price = document.querySelector("#price");
const hint = document.querySelector("#hint");
price.addEventListener("mouseover", () => {
hint.textContent = "Includes free delivery.";
console.log("Pointer is over the price.");
});
price.dispatchEvent(new MouseEvent("mouseover", { bubbles: true }));
console.log("Hint text:", hint.textContent);
</script>
Expected output:
Pointer is over the price.
Hint text: Includes free delivery.
Mouseout event
The pointer leaves. Together with mouseover it makes a full hover effect.
Show the hint on the way in, hide it on the way out
<p>Price: <span id="price">₹499</span></p>
<p id="hint"></p>
<script>
const price = document.querySelector("#price");
const hint = document.querySelector("#hint");
price.addEventListener("mouseover", () => {
hint.textContent = "Includes free delivery.";
});
price.addEventListener("mouseout", () => {
hint.textContent = "";
});
price.dispatchEvent(new MouseEvent("mouseover", { bubbles: true }));
console.log("While hovering:", JSON.stringify(hint.textContent));
price.dispatchEvent(new MouseEvent("mouseout", { bubbles: true }));
console.log("After leaving: ", JSON.stringify(hint.textContent));
</script>
Expected output:
While hovering: "Includes free delivery."
After leaving: ""
Why the names? The pointer moves over the element, then out.
For a colour change only, CSS :hover is simpler. Use these events when the page must do something.
Keydown event
Fires the moment a key is pressed. Event object event.key says which key ("Enter", "Escape"). It repeats while held.
React to Enter and Escape in a search box
<input id="search" placeholder="Search products">
<p id="status"></p>
<script>
const search = document.querySelector("#search");
const status = document.querySelector("#status");
search.addEventListener("keydown", (event) => {
console.log("keydown:", event.key);
if (event.key === "Enter") status.textContent = "Searching…";
if (event.key === "Escape") status.textContent = "Search cancelled.";
});
search.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true }));
console.log("Status:", status.textContent);
search.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true }));
console.log("Status:", status.textContent);
</script>
Expected output:
keydown: Enter
Status: Searching…
keydown: Escape
Status: Search cancelled.
Keyup event
Fires once when the key is released. (A key event sent by a script does not type into the field.)
Show the last key released
<input id="name" placeholder="Type your name">
<p id="last"></p>
<script>
const nameField = document.querySelector("#name");
const last = document.querySelector("#last");
nameField.addEventListener("keydown", (event) => console.log("down:", event.key));
nameField.addEventListener("keyup", (event) => {
console.log("up: ", event.key);
last.textContent = `Last key released: ${event.key}`;
});
for (const key of ["A", "s", "h", "a"]) {
nameField.dispatchEvent(new KeyboardEvent("keydown", { key, bubbles: true }));
nameField.dispatchEvent(new KeyboardEvent("keyup", { key, bubbles: true }));
}
console.log(last.textContent);
console.log("Field value:", JSON.stringify(nameField.value));
</script>
Expected output:
down: A
up: A
down: s
up: s
down: h
up: h
down: a
up: a
Last key released: a
Field value: ""
keydown for shortcuts and held keys; keyup to act once on release; input to react to the text itself.
Change event
Fires when the person has finished changing a value (for a text field: after leaving it). Changing .value in code fires nothing.
Update the delivery cost when the drop-down changes
<label>Delivery
<select id="delivery">
<option value="standard">Standard</option>
<option value="express">Express</option>
</select>
</label>
<p id="cost">Delivery: ₹0</p>
<script>
const delivery = document.querySelector("#delivery");
const cost = document.querySelector("#cost");
const prices = { standard: 0, express: 99 };
delivery.addEventListener("change", () => {
cost.textContent = `Delivery: ₹${prices[delivery.value]}`;
console.log("change fired, value is", delivery.value);
});
delivery.value = "express";
delivery.dispatchEvent(new Event("change", { bubbles: true }));
console.log(cost.textContent);
</script>
Expected output:
change fired, value is express
Delivery: ₹99
Input event
Fires on every change: each keystroke, paste or deletion. Good for live counters and search.
A live character counter
<textarea id="review" maxlength="60" placeholder="Write a short review"></textarea>
<p id="counter">0 / 60</p>
<script>
const review = document.querySelector("#review");
const counter = document.querySelector("#counter");
review.addEventListener("input", () => {
counter.textContent = `${review.value.length} / 60`;
});
for (const text of ["G", "Gr", "Great", "Great mug"]) {
review.value = text;
review.dispatchEvent(new Event("input", { bubbles: true }));
console.log(JSON.stringify(text), "→", counter.textContent);
}
</script>
Expected output:
"G" → 1 / 60
"Gr" → 2 / 60
"Great" → 5 / 60
"Great mug" → 9 / 60
| Event | When it fires on a text field |
|---|---|
input | after every change to the value, while typing |
change | once, when the person leaves the field after changing it |
Submit event
Fires on the form when it is sent (button click or Enter). event.preventDefault() stops the page reload so your code can handle the data.
Handle a sign-up form without reloading the page
<form id="signup">
<input name="email" value="asha@example.com">
<button type="submit">Sign up</button>
</form>
<p id="result"></p>
<script>
const signup = document.querySelector("#signup");
const result = document.querySelector("#result");
signup.addEventListener("submit", (event) => {
event.preventDefault();
const email = signup.elements.email.value;
result.textContent = `Thanks! We will write to ${email}.`;
console.log("submit handled, page did not reload");
});
signup.requestSubmit();
console.log(result.textContent);
</script>
Expected output:
submit handled, page did not reload
Thanks! We will write to asha@example.com.
Listen for submit on the form, not click on the button. A button click misses the Enter key.
Focus event
Focus = the element receiving keyboard input. focus fires when a field is clicked into or reached with Tab.
Show a tip while the password field has focus
<input id="password" type="password" placeholder="Choose a password">
<p id="tip"></p>
<script>
const password = document.querySelector("#password");
const tip = document.querySelector("#tip");
password.addEventListener("focus", () => {
tip.textContent = "Use at least 8 characters.";
console.log("focus fired");
});
password.dispatchEvent(new FocusEvent("focus"));
console.log("Tip:", tip.textContent);
</script>
Expected output:
focus fired
Tip: Use at least 8 characters.
Blur event
Fires when a field loses focus: the natural moment to check what was typed.
Why "blur"? The opposite of focus, like a camera lens.
Check an email field when the person leaves it
<input id="email" placeholder="Email address">
<p id="error"></p>
<script>
const email = document.querySelector("#email");
const error = document.querySelector("#error");
email.addEventListener("focus", () => {
error.textContent = "";
});
email.addEventListener("blur", () => {
error.textContent = email.value.includes("@") ? "" : "Please enter a valid email.";
console.log("blur fired, value was", JSON.stringify(email.value));
});
email.value = "asha.example.com";
email.dispatchEvent(new FocusEvent("blur"));
console.log("Error:", JSON.stringify(error.textContent));
email.dispatchEvent(new FocusEvent("focus"));
email.value = "asha@example.com";
email.dispatchEvent(new FocusEvent("blur"));
console.log("Error:", JSON.stringify(error.textContent));
</script>
Expected output:
blur fired, value was "asha.example.com"
Error: "Please enter a valid email."
blur fired, value was "asha@example.com"
Error: ""
focus and blur do not travel up to parents. Use focusin and focusout to catch every field with one listener.
addEventListener()
element.addEventListener("click", handler); // run on every click
element.addEventListener("click", handler, { once: true }); // run on the first click only
event.type is the event name; event.target is the element it happened on. One element can have many listeners, run in order.
One element can have several listeners, and each one gets the event
<button id="buy" type="button" data-product="Ceramic mug">Buy now</button>
<script>
const buy = document.querySelector("#buy");
buy.addEventListener("click", (event) => {
console.log("type: ", event.type);
console.log("target:", event.target.id);
console.log("product:", event.target.dataset.product);
});
buy.addEventListener("click", () => {
console.log("a second listener on the same button");
});
buy.addEventListener("click", () => {
console.log("this one runs only on the first click");
}, { once: true });
buy.click();
console.log("--- second click ---");
buy.click();
</script>
Expected output:
type: click
target: buy
product: Ceramic mug
a second listener on the same button
this one runs only on the first click
--- second click ---
type: click
target: buy
product: Ceramic mug
a second listener on the same button
Old code uses button.onclick = handler. An element holds only one onclick, so a second one silently replaces the first.
removeEventListener()
Stops a handler. Pass the same event name and the same function: a named function works.
Stop listening after the offer is claimed
<button id="claim" type="button">Claim free delivery</button>
<script>
const claim = document.querySelector("#claim");
let claims = 0;
function claimOffer() {
claims += 1;
console.log("Offer claimed. Total claims:", claims);
claim.removeEventListener("click", claimOffer);
claim.textContent = "Offer claimed";
}
claim.addEventListener("click", claimOffer);
claim.click();
claim.click();
claim.click();
console.log("Claims after three clicks:", claims);
</script>
Expected output:
Offer claimed. Total claims: 1
Claims after three clicks: 1
Two identical-looking arrow functions are two different functions, so this removes nothing:
Removing an arrow function you wrote twice does nothing
<button id="save" type="button">Save</button>
<script>
const save = document.querySelector("#save");
let saves = 0;
save.addEventListener("click", () => { saves += 1; });
save.removeEventListener("click", () => { saves += 1; });
save.click();
console.log("Saves after removing:", saves);
</script>
Expected output:
Saves after removing: 1
Forms
A form groups controls (inputs, drop-downs, buttons). Events say when; controls say what was entered.
Form elements
| Element | Used for | Its value is read from |
|---|---|---|
<input> | one line of text, email, number, date | .value |
<input type="checkbox"> | a yes-or-no choice | .checked |
<input type="radio"> | one choice from a small group | .checked, on each radio |
<select> | one choice from a drop-down list | .value |
<textarea> | several lines of text | .value |
<button> | sending or resetting the form | not a value |
An order form with one of each kind of control
<form id="order">
<input name="customer" value="Asha">
<input name="quantity" type="number" value="2">
<input name="giftWrap" type="checkbox">
<label><input name="size" type="radio" value="small"> Small</label>
<label><input name="size" type="radio" value="large" checked> Large</label>
<select name="colour">
<option value="blue">Blue</option>
<option value="green" selected>Green</option>
</select>
<textarea name="note">Please leave it at the door.</textarea>
<button type="submit">Place order</button>
</form>
<script>
const order = document.querySelector("#order");
for (const control of order.elements) {
console.log(control.tagName.toLowerCase(), control.type, control.name || "(no name)");
}
</script>
Expected output:
input text customer
input number quantity
input checkbox giftWrap
input radio size
input radio size
select select-one colour
textarea textarea note
button submit (no name)
The name attribute labels each control inside the form.
Accessing form controls
document.querySelector(), form.querySelector(), or clearest: form.elements.email.
Three ways to reach the same field
<form id="login">
<input id="login-email" name="email" value="asha@example.com">
<input name="password" type="password" value="sunrise42">
</form>
<script>
const login = document.querySelector("#login");
const byId = document.querySelector("#login-email");
const byName = login.elements.email;
const byBrackets = login.elements["email"];
console.log("Same element each time?", byId === byName && byName === byBrackets);
console.log("Controls in the form:", login.elements.length);
console.log("Password field type:", login.elements.password.type);
</script>
Expected output:
Same element each time? true
Controls in the form: 2
Password field type: password
Search inside the form. Two forms can both have a field named email; form.elements.email picks the right one.
Reading form values
.value for most controls (always a string, even for type="number"); .checked for checkboxes and radios.
Read every kind of value from the order form
<form id="order">
<input name="customer" value="Asha">
<input name="quantity" type="number" value="2">
<input name="giftWrap" type="checkbox" checked>
<select name="colour">
<option value="blue">Blue</option>
<option value="green" selected>Green</option>
</select>
</form>
<script>
const fields = document.querySelector("#order").elements;
console.log("customer:", fields.customer.value);
console.log("quantity:", fields.quantity.value, typeof fields.quantity.value);
console.log("quantity as a number:", fields.quantity.valueAsNumber);
console.log("giftWrap:", fields.giftWrap.checked);
console.log("colour:", fields.colour.value);
</script>
Expected output:
customer: Asha
quantity: 2 string
quantity as a number: 2
giftWrap: true
colour: green
new FormData(form) collects every named value at once. An unchecked checkbox is left out.
Collect the whole form at once with FormData
<form id="order">
<input name="customer" value="Asha">
<input name="quantity" type="number" value="2">
<input name="giftWrap" type="checkbox">
<select name="colour">
<option value="blue" selected>Blue</option>
<option value="green">Green</option>
</select>
<button type="submit">Place order</button>
</form>
<script>
const order = document.querySelector("#order");
order.addEventListener("submit", (event) => {
event.preventDefault();
const values = Object.fromEntries(new FormData(order));
console.log(values);
});
order.requestSubmit();
</script>
Expected output:
{
"customer": "Asha",
"quantity": "2",
"colour": "blue"
}
Updating form values
Assign to .value and .checked. form.reset() puts every control back to its starting value.
Fill in a saved address, then reset the form
<form id="address">
<input name="city" value="">
<input name="pincode" value="">
<input name="saveForLater" type="checkbox">
<button type="button" id="fill">Use my saved address</button>
</form>
<script>
const address = document.querySelector("#address");
const fields = address.elements;
document.querySelector("#fill").addEventListener("click", () => {
fields.city.value = "Chennai";
fields.pincode.value = "600001";
fields.saveForLater.checked = true;
});
document.querySelector("#fill").click();
console.log("After filling:", fields.city.value, fields.pincode.value, fields.saveForLater.checked);
address.reset();
console.log("After reset: ", JSON.stringify(fields.city.value), fields.saveForLater.checked);
</script>
Expected output:
After filling: Chennai 600001 true
After reset: "" false
Read and write with the same property. Writing from code fires no input/change, so dispatch one if other code listens.
Basic form validation
Check values in the submit handler; show messages and return early if a check fails. novalidate turns off the browser's own checks.
Check the email and quantity before accepting an order
<form id="order" novalidate>
<input name="email" value="asha.example.com">
<input name="quantity" type="number" value="0">
<button type="submit">Place order</button>
</form>
<p id="errors"></p>
<script>
const order = document.querySelector("#order");
const errors = document.querySelector("#errors");
order.addEventListener("submit", (event) => {
event.preventDefault();
const problems = [];
if (!order.elements.email.value.includes("@")) {
problems.push("Email needs an @.");
}
if (order.elements.quantity.valueAsNumber < 1) {
problems.push("Quantity must be at least 1.");
}
if (problems.length > 0) {
errors.textContent = problems.join(" ");
console.log("Rejected:", problems);
return;
}
errors.textContent = "Order placed.";
console.log("Accepted");
});
order.requestSubmit();
order.elements.email.value = "asha@example.com";
order.elements.quantity.value = "3";
order.requestSubmit();
console.log(errors.textContent);
</script>
Expected output:
Rejected: [
"Email needs an @.",
"Quantity must be at least 1."
]
Accepted
Order placed.
Built-in validation: required, type="email" and min="1" describe a valid value, and the browser refuses to submit until they pass.
Let the browser check required and min for you
<form id="order">
<input name="email" type="email" required>
<input name="quantity" type="number" min="1" value="0">
<button type="submit">Place order</button>
</form>
<script>
const order = document.querySelector("#order");
const { email, quantity } = order.elements;
let submitted = false;
order.addEventListener("submit", (event) => {
event.preventDefault();
submitted = true;
});
console.log("email valid? ", email.checkValidity(), "- missing:", email.validity.valueMissing);
console.log("quantity valid?", quantity.checkValidity(), "- too small:", quantity.validity.rangeUnderflow);
order.requestSubmit();
console.log("submit event fired?", submitted);
email.value = "asha@example.com";
quantity.value = "1";
console.log("whole form valid now?", order.checkValidity());
order.requestSubmit();
console.log("submit event fired?", submitted);
</script>
Expected output:
email valid? false - missing: true
quantity valid? false - too small: true
submit event fired? false
whole form valid now? true
submit event fired? true
Browser checks help people, but do not protect your data. The server must check again.
Events in the Editor
A full order form in the live editor: a live name preview on input, a check on blur, and one submit handler with validation.
An order form with input, blur and submit events
const form = document.getElementById("order");
const name = form.elements.customer;
const qty = form.elements.qty;
const result = document.getElementById("result");
name.addEventListener("input", () => {
result.textContent = name.value ? `Hello, ${name.value}!` : "Fill in the form and press Place order.";
});
qty.addEventListener("blur", () => {
qty.style.borderColor = qty.valueAsNumber >= 1 ? "" : "crimson";
});
form.addEventListener("submit", (event) => {
event.preventDefault();
const problems = [];
if (name.value.trim() === "") problems.push("Enter your name.");
if (!(qty.valueAsNumber >= 1)) problems.push("Quantity must be 1 or more.");
if (problems.length) {
result.textContent = problems.join(" ");
return;
}
result.textContent = `Order placed: ${qty.valueAsNumber} × size ${form.elements.size.value} for ${name.value}.`;
console.log(Object.fromEntries(new FormData(form)));
});
Leave the name empty and press Place order, then type a name. The input event updates the greeting on every key.
Easy way to remember: input = while typing, change = after, blur = on leaving, submit = on sending.
TL;DR
addEventListener(name, fn); passfn, notfn().- Read
event.key,event.typeandevent.targetfrom the event object. inputevery change,changewhen done,submiton the form withpreventDefault().- Remove with the same named function;
{ once: true }removes itself. - Read
.value(a string) or.checked;FormDatacollects all; validate before use.
Try this
In the Input event box, change "input" to "change" in both places. The printed lines stay the same, but typing in the box no longer counts until you leave it.
Check Yourself
Common mistakes
| Mistake | Wrong idea | Correct idea | What goes wrong |
|---|---|---|---|
addEventListener("click", handler()) | Brackets are needed | Pass handler | It runs once at load |
No preventDefault() in submit | Forms stay put | The page reloads | Your message vanishes |
click on the submit button | It catches every send | Use submit on the form | Enter is missed |
| Removing a new arrow function | Same code, same function | Keep a named function | Nothing is removed |
qty.value + 1 | .value is a number | Use valueAsNumber or Number() | "21" instead of 3 |
Setting .value and expecting input | Code changes fire events | Dispatch an Event | Live counters do not update |
Quick reference
| Syntax | Meaning |
|---|---|
el.addEventListener("click", handler) | call handler every time the event happens on el |
el.addEventListener("click", handler, { once: true }) | call it the first time only, then remove it |
el.removeEventListener("click", handler) | stop calling it, using the same function that was added |
click, dblclick | the element was clicked once, or twice quickly |
mouseover, mouseout | the pointer moved onto, or off, the element |
keydown, keyup | a key was pressed, or released; read event.key |
input, change | a value changed, on every edit or once when finished |
submit | the form was sent; call event.preventDefault() to stay on the page |
focus, blur | the element gained, or lost, keyboard focus |
event.target | the element the event happened on |
el.dispatchEvent(new Event("input", { bubbles: true })) | send an event from code, as if it really happened |
form.elements.email | the control named email inside the form |
field.value, box.checked | read or write a control's value |
Object.fromEntries(new FormData(form)) | every named value in the form, as an object |
form.reset() | put every control back to its starting value |
field.checkValidity() | true when the value follows required, min and similar rules |
Exercises
What to Remember
- Watch an event, run a function.
- Pick the right event for the moment you need.
- Read form values carefully, and always validate.
Next: DOM Traversal, Collections and Animation. Move between related elements, work with lists of elements, and animate them.