JavaScript Learning Guide – Module 5: Events
1. What are Events?
Events are actions that happen in the browser, like clicks, key presses, or form submissions.
JavaScript can respond to these events using event listeners.
2. Adding Event Listeners
We can use addEventListener() to respond to events.
// Example HTML: <button id="btn">Click Me</button>
let button = [Link]("btn");
[Link]("click", function() {
alert("Button was clicked!");
});
3. Common Events
Some frequently used events are click, input, change, submit, mouseover, and keydown.
// Example HTML: <input id="nameInput" placeholder="Type your name">
let input = [Link]("nameInput");
[Link]("input", function() {
[Link]("User typed: " + [Link]);
});
4. Event Bubbling & Delegation
Event bubbling means an event moves up the DOM tree. Event delegation uses this feature to
handle multiple elements with one listener.
// Example HTML: <ul id="list"><li>Item 1</li><li>Item 2</li></ul>
let list = [Link]("list");
[Link]("click", function(event) {
if([Link] === "LI") {
alert("You clicked: " + [Link]);
}
});
■ Mini Task: Form Validation
Create a simple form that checks if email and password fields are filled before submission.
// Example HTML:
// <form id="loginForm">
// <input id="email" type="email" placeholder="Email">
// <input id="password" type="password" placeholder="Password">
// <button type="submit">Login</button>
// </form>
[Link]("loginForm").addEventListener("submit", function(event) {
let email = [Link]("email").value;
let password = [Link]("password").value;
if(email === "" || password === "") {
alert("Both fields are required!");
[Link](); // Stop form from submitting
}
});
■ End of Module 5. In the next module, we will learn about ES6+ Features.