Events and Forms: Reacting to the Visitor
Respond to clicks, typing and form submission with event listeners, use event delegation, validate input with built-in HTML constraints, and test the behaviour automatically by dispatching events.
In this lesson you will
- Attach event listeners
- Use event delegation
- Validate with HTML attributes
- Test events by dispatching them
About 28 minutes
Letting customers order a loaf
Ravi wants customers to reserve bread. A reservation form needs a name, an email address, a quantity and a pickup note. Pages react to the user through events: a click, a key press, a change of value, a submit. You attach a function to an element with addEventListener, and the browser calls it with an event object that says what happened and where. For a list of many items, instead of attaching a listener to every item you attach one to the list and look at event.target, which says which child was clicked. This is called event delegation, and it also works for items added later.
HTML has validation built in, which you should use before writing your own. Attributes such as required, min, max, type=”email” and pattern declare the rules, and the browser knows how to check them: form.checkValidity() says whether all fields pass, and each field has a validity object with flags such as valueMissing, typeMismatch and rangeUnderflow. A submit handler normally calls event.preventDefault() to stop the page from reloading, so the script can send the data itself. Remember that client-side validation is only a convenience for the visitor: the server must always check again, because anyone can send requests without using your form.
const { JSDOM } = require('jsdom');
const dom = new JSDOM(`<!doctype html><body>
<ul id="menu"><li data-price="4.5">Sourdough</li><li data-price="4">Rye</li><li data-price="2.8">Baguette</li></ul>
<form id="order" novalidate>
<input id="name" required minlength="2">
<input id="email" type="email" required>
<input id="qty" type="number" min="1" max="10" value="1">
<button type="submit">Reserve</button>
</form><p id="total"></p></body>`);
const w = dom.window, d = w.document;
const log = [];
const cart = [];
d.getElementById('menu').addEventListener('click', e => {
const li = e.target.closest('li');
if (!li) return;
cart.push({ name: li.textContent, price: Number(li.dataset.price) });
d.getElementById('total').textContent = 'Total: ' + cart.reduce((s, c) => s + c.price, 0).toFixed(2);
log.push('clicked ' + li.textContent);
});
const form = d.getElementById('order');
form.addEventListener('submit', e => { e.preventDefault(); log.push('submit ok=' + form.checkValidity()); });
function fire(el, type) { el.dispatchEvent(new w.Event(type, { bubbles: true, cancelable: true })); }
d.querySelectorAll('#menu li').forEach(li => li.dispatchEvent(new w.MouseEvent('click', { bubbles: true })));
d.querySelectorAll('#menu li')[0].dispatchEvent(new w.MouseEvent('click', { bubbles: true }));
console.log(d.getElementById('total').textContent, '| cart items:', cart.length);
function state(id, value) { const el = d.getElementById(id); el.value = value; const v = el.validity; return { id, value, valid: el.checkValidity(), missing: v.valueMissing, mismatch: v.typeMismatch, tooShort: v.tooShort, under: v.rangeUnderflow, over: v.rangeOverflow }; }
const checks = [state('name', ''), state('name', 'R'), state('name', 'Ravi'), state('email', 'ravi@example'), state('email', 'ravi at example.com'), state('email', 'ravi@example.com'), state('qty', '0'), state('qty', '11'), state('qty', '3')];
checks.forEach(c => console.log(JSON.stringify(c)));
form.dispatchEvent(new w.Event('submit', { bubbles: true, cancelable: true }));
console.log(log.join(' | '));
console.log('DATA ' + JSON.stringify({ total: cart.reduce((s, c) => s + c.price, 0), n: cart.length, checks, log }));
Total: 15.80 | cart items: 4
{"id":"name","value":"","valid":false,"missing":true,"mismatch":false,"tooShort":false,"under":false,"over":false}
{"id":"name","value":"R","valid":true,"missing":false,"mismatch":false,"tooShort":false,"under":false,"over":false}
{"id":"name","value":"Ravi","valid":true,"missing":false,"mismatch":false,"tooShort":false,"under":false,"over":false}
{"id":"email","value":"ravi@example","valid":true,"missing":false,"mismatch":false,"tooShort":false,"under":false,"over":false}
{"id":"email","value":"ravi at example.com","valid":false,"missing":false,"mismatch":true,"tooShort":false,"under":false,"over":false}
{"id":"email","value":"ravi@example.com","valid":true,"missing":false,"mismatch":false,"tooShort":false,"under":false,"over":false}
{"id":"qty","value":"0","valid":false,"missing":false,"mismatch":false,"tooShort":false,"under":true,"over":false}
{"id":"qty","value":"11","valid":false,"missing":false,"mismatch":false,"tooShort":false,"under":false,"over":true}
{"id":"qty","value":"3","valid":true,"missing":false,"mismatch":false,"tooShort":false,"under":false,"over":false}
clicked Sourdough | clicked Rye | clicked Baguette | clicked Sourdough | submit ok=true
The test script dispatched click events at the three menu items and then at the first one again, and one listener on the list handled all four through event.target.closest(“li”). The cart has 4 items and the total is 15.8, which is 4.5 + 4.0 + 2.8 + 4.5. The same listener would work for items added to the list later, which is the main benefit of delegation. Dispatching events from a script, with new Event or new MouseEvent, is how automated tests press buttons without a person: the same listeners run as for a real click.
The validation checks show what the browser knows from the attributes alone. An empty required name has valueMissing, the name “R” is too short only when typed by a user (the minlength rule applies to user edits, so a script-set value is not flagged), and “Ravi” is valid. The email “ravi@example” is accepted, which surprises many people: the HTML standard allows an address with no dot in the domain, and “ravi at example.com” is rejected because it has no @. A quantity of 0 underflows the minimum, 11 overflows the maximum and 3 is valid. The last log entry, “submit ok=true”, comes from the submit handler, which called preventDefault so that the page would not reload, and reported whether the whole form was valid at that moment.
Independent check: the HTML standard gives a regular expression for a valid email address. A Python version of it, applied to the three addresses, agrees with the browser-like validation of jsdom for each of them: it accepts “ravi@example” and “ravi@example.com” and rejects the one with spaces. That regular expression is deliberately simple: it does not prove that the mailbox exists, and the only real test of an email address is to send a message to it.
Check by hand: 4.5 + 4.0 + 2.8 = 11.3 for one of each, and adding the sourdough once more gives 15.8. The quantity field allows 1 to 10, so 0 is below the minimum and 11 is above the maximum, and 3 passes.
Client-side checks make forms friendlier, and they stop nobody. Anyone can send a request that skips your form. The back end must treat every value as untrusted.
Use the validity flags to show a specific message next to the field, such as “Enter an email address like name@example.com”. Colour alone is not enough, and a message that is not linked to the field is missed by screen reader users.
Every program in this lesson was run while the course was written, with Node.js 22, jsdom 31 (a pure-JavaScript DOM used for tests, not a real browser) and Python 3.13. Browsers, tools and their menus change often, so check the official documentation (MDN, the Node.js docs, your provider) for current behaviour. Validation messages and some rules differ slightly between browsers, so test in the browsers your visitors use.
Practice
Add a pattern attribute that accepts only a pickup time such as 07:30, and test five values. Show the error text in a p element linked with aria-describedby. Handle the keydown event to submit with the Enter key in the quantity field.
Check what you learned
Five quick questions. Pick an answer and you will see straight away whether it is right and why.
What is event delegation?
- One listener per child
- A server feature
- A CSS rule
- One listener on a parent handles events from its children
Use event.target.closest().
What does preventDefault do in a submit handler?
- Deletes the form
- Validates the form
- Stops the browser from reloading the page
- Sends the data
Your script takes over.
Which attribute makes a field mandatory?
- must
- need
- required
- mandatory
Validated by the browser.
Why must the server validate again?
- Browsers cannot validate
- Anyone can send requests without your form
- It is faster
- It is required by HTML
Client checks are a convenience.
How can tests simulate a click?
- By restarting the page
- By dispatching a click event
- By editing the HTML
- They cannot
new MouseEvent(“click”).
Summary
- Events connect user actions to code; use addEventListener.
- Delegation uses one listener on a parent.
- HTML attributes give free validation; the server must validate too.
- Dispatch events in tests to check behaviour.
Questions
What is the difference between input and change events?
input fires on every edit, while change fires when the value is committed, for example when the field loses focus.
Should I use onclick attributes in HTML?
Prefer addEventListener in a script. It keeps behaviour out of the markup and allows several listeners per element.
How do I validate a phone number?
Phone formats vary by country. Prefer a simple rule, such as digits and a few separators, and confirm by sending a code, rather than a strict pattern. Check local conventions.
