JavaScript Events
# JavaScript Events
Websites are not meant to be static documents; they are meant to be interacted with. When a user hovers over a card, clicks a button, types in a search bar, or scrolls down the page, the browser fires an Event.
In this chapter, we will learn how to "listen" for these events and execute JavaScript code in response to them.
1. Introduction
HTML events are "things" that happen to HTML elements. JavaScript can be instructed to listen for these events using Event Listeners.
Previously, we used onclick="myFunction()" directly in our HTML. While this works, it violates the principle of separation of concerns (mixing structure with behavior). Modern JavaScript uses addEventListener() to handle events entirely inside the .js file.
2. Learning Objectives
By the end of this chapter, you will be able to:
- Identify common HTML events (clicks, hovers, keyboard inputs).
-
Attach events using
addEventListener().
-
Use the
Eventobject to get information about the interaction.
- Remove event listeners.
- Build an Interactive Button Effects mini-project.
3. Common HTML Events
Here is a list of the most common events you will use:
-
Mouse Events:
click,dblclick,mouseenter,mouseleave
-
Keyboard Events:
keydown,keyup,keypress
-
Form Events:
submit,change,input,focus,blur
-
Window Events:
load,resize,scroll
4. addEventListener()
The addEventListener() method attaches an event handler to a specific element without overwriting existing event handlers.
*Note: We drop the "on" prefix. It is click, not onclick.*
---
5. Real-world Examples & Code Snippets
Example 1: The Modern Click Event
HTML:
JavaScript:
Example 2: Calling a Named Function
Instead of writing the function directly inside the listener (an anonymous function), you can pass the name of an existing function.
*Why no ()? If you write turnRed(), the function runs immediately when the page loads, rather than waiting for the click.*
Example 3: Mouse Enter and Leave (Hover)
Example 4: The Event Object (e or event)
When an event occurs, the browser automatically creates an Event Object containing massive amounts of data about the event (Where was the mouse? Which key was pressed?). It is passed as the first parameter to your function.
Example 5: Keyboard Events (keyup)
Listening to what the user types.
Example 6: The input Event (Real-time tracking)
Unlike keyup, the input event fires immediately every time the value of the input changes, even if they paste text with a mouse.
Example 7: The change Event
The change event fires only when the user finishes interacting and "commits" the change (e.g., clicking away from the input, or selecting an option from a dropdown).
Example 8: Form submit and preventDefault()
When a user submits an HTML form, the default browser behavior is to refresh the page. In modern apps, we want to stop this refresh and handle the data with JS. We use event.preventDefault().
Example 9: Multiple Listeners on One Element
You can attach multiple different events to the same element without overwriting them.
Example 10: Event Delegation
If you have a list of 100 items, adding 100 event listeners is bad for performance. Instead, you add ONE listener to the parent <ul>, and let the events "bubble up".
---
7. Common Mistakes for Beginners
-
1.
Adding
()to a named function in addEventListener:
btn.addEventListener("click", myFunc()); // BAD! Runs immediately.
btn.addEventListener("click", myFunc); // GOOD! Runs on click.
-
2.
Forgetting
preventDefault()on forms: If you forget this, your JS code might run for a split second, but then the page refreshes and all your data is lost.
-
3.
Using
event.targetvsevent.currentTarget:targetis the exact element clicked (maybe an icon inside a button).currentTargetis the element the listener is attached to (the button itself).
8. Best Practices
-
Always separate HTML and JS. Remove all
onclick=""attributes from your HTML files.
-
Use
event.preventDefault()on all forms.
- Use Event Delegation when dealing with lists or dynamically created elements.
9. Mini Project: Interactive Button Effects
Let's build a UI with buttons that track mouse coordinates and generate ripple effects.
HTML:
events.js:
10. Exercises
-
1.
Create a
<div>in HTML. Write JS to add an event listener that console logs "Hovering!" when the mouse enters it.
-
2.
Add an event listener to the
documentthat listens forkeydown. If the user presses the "Escape" key, trigger an alert.
-
3.
Why is
event.preventDefault()necessary when dealing with HTML<form>submissions?
11. MCQs (Multiple Choice Questions)
Q1: What is the correct way to add a click event in modern JavaScript?
A) btn.onClick = function()
B) btn.addEventListener("click", function())
C) btn.attachEvent("click", function())
D) btn.addEventListener("onclick", function())
*Answer: B*
Q2: What is the purpose of the Event object (e) passed to an event listener?
A) To stop the event.
B) To hold data about the event (like mouse coordinates or keys pressed).
C) To change the CSS of the element.
D) To trigger a second event.
*Answer: B*
Q3: Which event fires continuously as the user types into an input field?
A) change
B) submit
C) input
D) blur
*Answer: C*
12. Interview Questions
Q: Explain Event Bubbling.
*A: Event Bubbling is a mechanism where an event triggered on a deeply nested element (like a <span> inside a <button> inside a <div>) will "bubble up" and trigger listeners on all of its parent elements, all the way up to the document. You can stop this using event.stopPropagation().*
Q: What is Event Delegation?
*A: Event Delegation is a pattern based on Event Bubbling. Instead of attaching 100 event listeners to 100 child elements, you attach ONE listener to the parent element. When a child is clicked, the event bubbles up to the parent, and you use event.target to figure out which child initiated the event.*
13. FAQs
Q: Should I use Arrow Functions for Event Listeners?
*A: Yes, mostly. But be careful: in standard functions, this refers to the element that was clicked. In arrow functions, this is inherited from the surrounding scope, which can cause bugs if you rely on it. It is usually safer to use event.currentTarget.*
14. Summary
-
Use
addEventListener(event, function)to listen for user interactions.
-
Common events:
click,mouseenter,keyup,submit,input.
-
The Event object (
eventore) contains data about the interaction.
-
event.targettells you exactly what element was interacted with.
-
Use
event.preventDefault()to stop forms from refreshing the page.