0% found this document useful (0 votes)
18 views

JavaScript DOM Event Listeners_ Comprehensive Guide

Uploaded by

contraste visual
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

JavaScript DOM Event Listeners_ Comprehensive Guide

Uploaded by

contraste visual
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

JavaScript DOM Event Listeners: Comprehensive Guide

JavaScript DOM Event Listeners: Comprehensive Guide 1


What are Event Listeners? 2
Common Events: 2
Basic Syntax 3
Adding an Event Listener 3
Example: Click Event 3

Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis

1
Removing an Event Listener 3
Event Object 3
Example: Access Event Properties 3
Event Propagation 4
Example: Bubbling vs. Capturing 4
Event Delegation 4
Example: Event Delegation 4
Prevent Default Behavior 5
Example: Prevent Default 5
Detailed Examples 5
Example 1: Toggle Class on Button Click 5
Example 2: Key Press Event 6
Exercises 6
Exercise 1: Button Counter 6
Solution: 6
Exercise 2: Dynamic List 6
Solution: 6
Exercise 3: Keyboard Navigation 7
Multiple-Choice Questions 7
Question 1: 7
Question 2: 7
Question 3: 8
Best Practices for Event Listeners 8

Event listeners allow JavaScript to detect and respond to user interactions or changes in the
DOM. This guide explains event listeners, their usage, examples, exercises, and quiz questions
to help you master this critical aspect of web development.

What are Event Listeners?

Event listeners are functions or handlers that wait for specific events, such as clicks, key
presses, or mouse movements, and execute code in response.

Common Events:

1. Mouse Events: click, dblclick, mouseover, mouseout, mousedown, mouseup


2. Keyboard Events: keydown, keyup, keypress
3. Form Events: submit, change, input, focus, blur
4. Window Events: load, resize, scroll

Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis

2
Basic Syntax
element.addEventListener(event, callbackFunction);

● element: The target element to listen for events.


● event: The type of event (e.g., click, keydown).
● callbackFunction: The function to execute when the event occurs.

Adding an Event Listener

Example: Click Event


<button id="myButton">Click Me</button>
<script>
const button = document.getElementById("myButton");
button.addEventListener("click", () => {
alert("Button was clicked!");
});
</script>

Removing an Event Listener

Use removeEventListener to stop listening for an event.

function handleClick() {
alert("Button was clicked!");
}
const button = document.getElementById("myButton");
button.addEventListener("click", handleClick);
// Remove the event listener
button.removeEventListener("click", handleClick);

Event Object

The event object provides information about the event, such as the target element and mouse
position.

Example: Access Event Properties


document.addEventListener("click", (event) => {
console.log("Clicked element:", event.target);
console.log("Mouse position:", event.clientX, event.clientY);

Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis

3
});

Event Propagation

1. Event Bubbling: Events propagate from the target element to its ancestors.
2. Event Capturing: Events propagate from ancestors to the target element.

Example: Bubbling vs. Capturing


<div id="parent" style="padding: 50px; background: lightblue;">
Parent
<button id="child" style="margin: 20px;">Child</button>
</div>
<script>
const parent = document.getElementById("parent");
const child = document.getElementById("child");
parent.addEventListener(
"click",
() => {
alert("Parent clicked!");
},
true // Use capturing phase
);
child.addEventListener("click", (event) => {
alert("Child clicked!");
event.stopPropagation(); // Prevent event bubbling
});
</script>

Event Delegation

Event delegation involves attaching a single event listener to a parent element and handling
child element events through the event.target property.

Example: Event Delegation


<ul id="list">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis

4
<script>
const list = document.getElementById("list");
list.addEventListener("click", (event) => {
if (event.target.tagName === "LI") {
alert(`You clicked ${event.target.textContent}`);
}
});
</script>

Prevent Default Behavior

Some events, like form submissions or links, have default behaviors that can be prevented.

Example: Prevent Default


<a href="https://example.com" id="link">Go to Example</a>
<script>
const link = document.getElementById("link");
link.addEventListener("click", (event) => {
event.preventDefault();
alert("Link click prevented!");
});
</script>

Detailed Examples

Example 1: Toggle Class on Button Click


<div id="box" style="width: 100px; height: 100px; background:
red;"></div>
<button id="toggleButton">Toggle Color</button>
<script>
const box = document.getElementById("box");
const button = document.getElementById("toggleButton");
button.addEventListener("click", () => {
box.classList.toggle("blue");
});
</script>
<style>
.blue {
background: blue;
Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis

5
}
</style>

Example 2: Key Press Event


<input type="text" id="input" placeholder="Type something" />
<p id="output"></p>
<script>
const input = document.getElementById("input");
const output = document.getElementById("output");
input.addEventListener("keyup", (event) => {
output.textContent = `You typed: ${event.key}`;
});
</script>

Exercises

Exercise 1: Button Counter

Create a button that counts how many times it has been clicked and displays the count.

Solution:
<button id="counterButton">Click me</button>
<p id="count">Count: 0</p>
<script>
const button = document.getElementById("counterButton");
const countDisplay = document.getElementById("count");
let count = 0;
button.addEventListener("click", () => {
count++;
countDisplay.textContent = `Count: ${count}`;
});
</script>

Exercise 2: Dynamic List

Create an input field and a button. When the button is clicked, add the input value as a new list
item.

Solution:
<input type="text" id="itemInput" placeholder="Enter item" />
Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis

6
<button id="addItemButton">Add Item</button>
<ul id="itemList"></ul>
<script>
const input = document.getElementById("itemInput");
const button = document.getElementById("addItemButton");
const list = document.getElementById("itemList");
button.addEventListener("click", () => {
const newItem = document.createElement("li");
newItem.textContent = input.value;
list.appendChild(newItem);
input.value = ""; // Clear input
});
</script>

Exercise 3: Keyboard Navigation

Create a box that moves up, down, left, or right based on arrow key presses.

Multiple-Choice Questions

Question 1:

Which method is used to attach an event listener to an element?

1. addListener()
2. addEventListener()
3. onEvent()
4. listenEvent()

Answer: 2. addEventListener()

Question 2:

What does event.stopPropagation() do?

1. Stops the event listener.


2. Prevents the default action.
3. Stops the event from bubbling up or capturing down.
4. Removes the event listener.

Answer: 3. Stops the event from bubbling up or capturing down.

Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis

7
Question 3:

Which property refers to the element that triggered the event?

1. event.currentTarget
2. event.sourceElement
3. event.target
4. event.listener

Answer: 3. event.target

Best Practices for Event Listeners

1. Use Delegation: Reduce memory usage by attaching listeners to parent elements.


2. Remove Listeners: Clean up unused listeners to avoid memory leaks.
3. Prevent Default Carefully: Use event.preventDefault() sparingly to avoid
breaking native behaviors.
4. Optimize Performance: Debounce or throttle listeners for high-frequency events like
scroll or mousemove.

Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis

You might also like