Handling forms and event propagation
This lesson applies JavaScript Events concepts to code you can run and adapt.
✓ What you will learn in this topic
- Explain key JavaScript Events concepts.
- Read and adapt the examples.
- Apply the idea to a small real interface or data task.
Concept explanation
Events, click/input/keyboard/mouse/form listeners, event objects, preventDefault, and event bubbling.
These concepts appear in everyday interfaces and data transformations; understanding the trade-offs helps you choose a reliable implementation.
Syntax
The examples use standard ECMAScript syntax. Run console examples in a browser console or Node.js; DOM examples require a browser page containing the referenced elements.
Example 1: a small experiment
Run this compact example to observe the core rule before applying it to a larger feature.
form.addEventListener('submit', (event) => {
event.preventDefault();
console.log(new FormData(form).get('email'));
});Expected output: Submitting the form is handled without navigating away; the email value is logged.
Why it is useful: A small experiment makes the value or behavior easy to inspect.
Example 2: a practical feature
This example models a small piece of application behavior. Adapt its values and inspect what changes.
button.addEventListener('click', (event) => {
console.log(event.type);
});Expected output: Clicking the button logs click.
Why it is useful: The same pattern can be extended into a real feature without tying the entire application to one large block of code.
Common mistakes
Registering a listener is not the same as calling it. Pass a function reference instead of invoking it during setup.
Best practices
Use addEventListener, inspect event.target/currentTarget, and delegate repeated child interactions to a stable parent.
Practice exercise
Listen for input changes to update a live character count, and prevent empty form submission.
Lesson summary
Events, click/input/keyboard/mouse/form listeners, event objects, preventDefault, and event bubbling.
Knowledge check
Which practice best avoids the common mistake in JavaScript Events?
Show explanation
Use addEventListener, inspect event.target/currentTarget, and delegate repeated child interactions to a stable parent.
Practical example
javascriptbutton.addEventListener('click', (event) => {
console.log(event.type);
});
Expected result:
Clicking the button logs click.
Hands-on practice task
Listen for input changes to update a live character count, and prevent empty form submission.
In this section
Other lessons in JavaScript Events
Broaden your knowledge
Related learning topics
CSS
Learn to style, lay out, and adapt interfaces with a complete course from CSS foundations through advanced responsive architecture.
HTML
Learn to structure accessible, meaningful web pages with a complete HTML course from first document to professional application patterns.