Lecture Notes Of Day 11
Event Handling in
JavaScript
Objective:
By the end of this class,
students will understand how to handle user interactions using events in
JavaScript.
Topics Covered:
1.Adding Event
Listeners
2.Event Types: click,
mouseover, keydown, submit
3.Event Propagation
4.Event.preventDefault()
1. Adding Event Listeners
Event handling in
JavaScript allows us to respond to user actions like clicks, typing, or
hovering. To set up event handling, we use Event Listeners.
An event listener is a
function that waits for a specific event (like a click or key press) to occur
on a particular element. Once that event is triggered, the function executes.
Syntax:
element.addEventListener(eventType,
function, useCapture);
- element:
The DOM element where the event is attached (e.g., a button or a form).
- eventType:
The type of event to listen for (e.g., "click",
"mouseover", "keydown", etc.).
- function:
The callback function that is executed when the event occurs.
- useCapture:
Optional parameter (default is false). It determines whether the event
should be handled during the capturing phase (true) or the bubbling phase
(false).
Example:
|
const button =
document.getElementById("myButton"); button.addEventListener("click",
function() { alert("Button
was clicked!"); }); |
Explanation:
In this example, when the
button with the ID "myButton" is clicked, the callback function will
display an alert saying "Button was clicked!".
2. Event Types: click,
mouseover, keydown, submit
JavaScript provides
various types of events that can be handled. Some common events include:
Click Event
The click event is
triggered when a user clicks on an element like a button or a link.
Example:
|
const button =
document.getElementById("myButton"); button.addEventListener("click",
function() { console.log("Button
clicked!"); }); |
Mouseover Event
The mouseover event
occurs when the mouse pointer hovers over an element.
Example:
|
const div =
document.getElementById("myDiv"); div.addEventListener("mouseover",
function() { div.style.backgroundColor
= "lightblue"; }); |
Explanation:
In this example, when the
mouse pointer hovers over the div with the ID "myDiv", the background
color of the div changes to light blue.
Keydown Event
The keydown event occurs
when a key is pressed down on the keyboard.
Example:
|
document.addEventListener("keydown",
function(event) { console.log(`Key
pressed: ${event.key}`); }); |
Explanation:
This example listens for
a keydown event on the entire document. When a key is pressed, it logs the name
of the key that was pressed (e.g., "a", "Enter", etc.).
Submit Event
The submit event is
triggered when a form is submitted.
Example:
|
const form =
document.getElementById("myForm"); form.addEventListener("submit",
function(event) { event.preventDefault(); console.log("Form
submission prevented"); }); |
Explanation:
This example listens for
the submit event on a form. The event.preventDefault() method is used to stop
the form from submitting, and the message "Form submission prevented"
is logged.
3. Event Propagation
Event propagation is the
process by which an event "bubbles up" or "captures" down
through the DOM tree. There are two phases of event propagation:
1. Capturing
Phase: The event starts from the root of the document and goes down to the
target element.
2. Bubbling
Phase: After the event reaches the target element, it bubbles back up to
the root of the document.
By default, events bubble
up. However, you can control the flow of the event with addEventListener().
Capturing vs Bubbling:
|
// Capturing phase
(default is false) element.addEventListener("click",
function() { console.log("Captured
during the capturing phase"); }, true); // Bubbling phase
(default is true) element.addEventListener("click",
function() { console.log("Captured
during the bubbling phase"); }, false); |
Explanation:
- The
first listener is using the capturing phase (true), so it will trigger
before the event bubbles up.
- The
second listener uses the default bubbling phase (false), so it will
trigger after the event reaches the target element.
4. event.preventDefault()
The
event.preventDefault() method prevents the default action of an event from
being triggered. It is useful in cases like preventing a form from submitting,
stopping a link from following its URL, or blocking other default browser
behavior.
Example 1: Preventing
Form Submission
|
const form =
document.getElementById("myForm"); form.addEventListener("submit",
function(event) { event.preventDefault();
// Prevents form submission console.log("Form
submission prevented"); }); |
Explanation:
This example prevents the
form from submitting when the submit button is clicked and instead logs a
message.
Example 2: Preventing
Link Navigation
|
const link =
document.getElementById("myLink"); link.addEventListener("click",
function(event) { event.preventDefault();
// Prevents the link from navigating console.log("Link
clicked, but no navigation occurred"); }); |
Explanation:
Here, when the link is
clicked, the default behavior (navigation to the link's href) is prevented, and
a message is logged instead.
Summary
- Event
Listeners are used to handle user
interactions with DOM elements.
- Common
event types include click, mouseover, keydown, and submit.
- Event
Propagation involves two phases: capturing
and bubbling.
- event.preventDefault() prevents
the default behavior of an event, such as preventing form submissions or
link navigation.
Practice Exercise:
1. Create an
event listener that changes the background color of a <div> when the
mouse hovers over it.
2. Set up a
form that shows a custom message when submitted but prevents the default form
submission.
3. Create a
button that, when clicked, will display an alert and prevent the default
behavior of the button (e.g., navigating away if it’s a link).
