smartyfy.mrindigi.com

Web Development Pro | Lesson 027 | Events and Predictable Interaction

Web Development Pro · Lesson 27 of 60

Module 3: JavaScript foundations

In this lesson

Prerequisites and learning outcomes

Complete lesson 26 first. This lesson builds on event listeners, default actions, and delegation. By the end, you can build controls that work with both keyboard and pointer input. Plan 10–15 minutes for the core explanation and additional time for the worked practice.

Respond to an action rather than polling the page

Events let the page react when something happens, such as a click, input change, or form submission. AddEventListener connects a handler to an event type without overwriting every other listener. The handler is called later when the event is dispatched; passing a function is different from calling it immediately while setting up the page.

This lesson builds a local seat-count selector with a maximum of three. It makes no reservation and sends no request. Native buttons provide the underlying keyboard activation behavior. Listening for click on a button can handle ordinary pointer activation and the click activation produced by keyboard use, avoiding a second custom key handler that could accidentally double-trigger the action.

Keep state and display synchronized

The count is application state. Button disabled properties and the status sentence are a view of that state. Update them together in one render function so the page cannot show three selected seats while still allowing an increase beyond the limit. The click handler changes state; render translates that state into the interface.

const controls = document.querySelector('#seat-controls');
const status = document.querySelector('#seat-status');
const increase = document.querySelector('#increase');
const decrease = document.querySelector('#decrease');
if (!controls || !status || !increase || !decrease) throw new Error('Seat controls missing.');
let selected = 0;
const maximum = 3;
function render() {
  status.textContent = `${selected} of ${maximum} demo seats selected.`;
  decrease.disabled = selected === 0;
  increase.disabled = selected === maximum;
}
controls.addEventListener('click', event => {
  if (!(event.target instanceof Element)) return;
  const button = event.target.closest('button[data-action]');
  if (!button || !controls.contains(button)) return;
  if (button.dataset.action === 'increase' && selected < maximum) selected += 1;
  if (button.dataset.action === 'decrease' && selected > 0) selected -= 1;
  render();
});
render();

The complete HTML supplies the two buttons inside seat-controls, with data-action values increase and decrease. Their ids match the selected references. The status paragraph has role="status" so updates can be announced politely by supporting assistive technology. It is a short message rather than a large live region containing the entire page.

Understand target and currentTarget

Event.target identifies where the event originated. Event.currentTarget identifies the element whose listener is currently running. If a button contains a span and that span is clicked, target may be the span. Calling closest finds the relevant button ancestor, allowing the handler to work even when the button's internal markup changes.

The listener is attached to the shared controls container. Click events normally bubble from descendants toward ancestors, so one listener can handle the buttons. This pattern is event delegation. The contains check ensures the discovered button belongs to the intended component, and the explicit action comparisons limit which data values are accepted.

Not every event bubbles in the same way, and shadow DOM can affect event paths. Do not generalize this exact pattern to all events without reading their behavior. For a small component, direct listeners on each button would also be reasonable. Delegation is a tool for a relationship, not a rule that every handler must live on body.

Distinguish default behavior from propagation

PreventDefault asks the browser not to perform an event's cancelable default action, such as a form submission or link navigation. StopPropagation affects travel through the event path. They solve different problems. Stopping bubbling does not automatically cancel navigation, and canceling navigation does not automatically stop other listeners from seeing the event.

These controls use type="button", so there is no form submission default to cancel. Correct HTML avoids unnecessary prevention logic. Later form handling will listen to submit and use preventDefault for a deliberate local-only workflow. Do not block default behavior reflexively, because native behavior often supplies important keyboard and navigation support.

Make repeated actions safe

The handler checks the state bounds even though the buttons are disabled at the limits. This keeps the calculation defensible if the handler is invoked unexpectedly or the DOM state is changed during debugging. Disabled controls improve the interface, while the explicit state condition preserves the local invariant.

Attach listeners once during setup. Adding a new listener every time render runs can make one click increment several times after repeated renders. Anonymous function objects created on each call are distinct listeners. Keep setup and rendering separate, and test repeated interactions rather than only the first click.

Test the complete state transition

Start at zero, increase to three, attempt one more increase, decrease to zero, and try an irrelevant click in the container. The status and disabled states should remain consistent. Also activate the controls by keyboard in a real browser and observe whether focus remains understandable when a button becomes disabled.

The provided runtime test invokes the registered listener with explicit event targets in a limited DOM double. It checks nested targets, irrelevant targets, bounds, and repeated actions. It does not simulate real bubbling, native disabled-event suppression, keyboard activation, focus movement, or screen-reader announcements. Those are separate manual browser gates.

Worked practice

Worked exercise 1: Handle a nested target

Task: A plus button contains a span around its text, and the span is clicked. Worked answer: use event.target.closest('button[data-action]') after ensuring target is an Element. Reading dataset.action directly from the span would miss the action stored on the button.

Worked exercise 2: Prevent duplicate listeners

Task: Every render adds another click listener, so the third click changes the count three times. Worked answer: move listener registration into one-time setup and keep render limited to updating the view. Then repeat the full increase/decrease journey to verify only one state transition occurs per activation.

Worked exercise 3: Separate two event controls

Task: A link should keep bubbling to an analytics listener but not navigate in a specific local demo. Worked answer: preventDefault cancels the navigation while leaving propagation intact. StopPropagation would address a different requirement and would not itself cancel the link's default navigation.

Knowledge check

Question 1

Which value identifies the element where the listener is attached? A) target. B) currentTarget. C) relatedTarget for every event. D) The element returned by the first closest call.

Check question 1: answer and explanation

Answer: B. Target and currentTarget can differ during event propagation.

Question 2

Why use closest for a delegated button action? A) The originating target may be a nested element. B) It automatically validates every action value. C) It confines the match to the listener container without any further check. D) It returns the first matching descendant of the target.

Check question 2: answer and explanation

Answer: A. Closest locates the relevant ancestor control from a nested target.

Question 3

What does preventDefault affect? A) Propagation to every later ancestor listener. B) Every other listener on the current element. C) A cancelable default action. D) Whether the event handler runs in the capture phase.

Check question 3: answer and explanation

Answer: C. It is distinct from stopping propagation.

Question 4

Why keep listener registration outside render? A) A listener registered in render automatically replaces all earlier ones. B) Every rerender needs a fresh listener on the unchanged container. C) Anonymous callbacks created during rerender are always treated as the same listener. D) Repeated setup can add duplicate handlers.

Check question 4: answer and explanation

Answer: D. One-time wiring avoids multiple responses to one action.

Question 5

What does the provided event-double test leave unverified? A) Actual browser bubbling, keyboard activation, and focus. B) The selected count in its modeled cases. C) The branch bounds it asserts. D) The status text it inspects.

Check question 5: answer and explanation

Answer: A. Modeled handler calls are narrower than real user interaction.

Sources and further reading