Events & Event Listeners
Make your pages interactive! Learn to handle clicks, keyboard input, mouse movements, and more with event listeners.
Make your pages interactive! Learn to handle clicks, keyboard input, mouse movements, and more with event listeners. This hands-on tutorial focuses on practical implementation of events & event listeners concepts.
Events & Event Listeners
A web page without events is just a digital poster. Events make it interactive! They allow your code to react when a user clicks, types, scrolls, or hovers.
1. What are Events? π
What is it? Signals fired by the browser when something interesting happens.
Common Events:
- Mouse:
click,dblclick,mouseenter,mouseleave - Keyboard:
keydown,keyup - Form:
submit,change,focus,blur - Window:
resize,scroll,load
2. Adding Event Listeners π
To react to an event, you attach an Event Listener to an element.
Method: element.addEventListener(event, callback)
3. The Event Object π¦
When an event happens, the browser automatically passes an Event Object to your function. It contains all the details about the event.
4. Preventing Default Behavior π
Some elements have default actions (e.g., links navigate to a new page, forms submit and reload). You can stop this using event.preventDefault().
5. Event Bubbling & Propagation π«§
Events in the DOM don't just happen on one element. They bubble up from the target element to its parents.
Flow: Button β‘οΈ Div β‘οΈ Body β‘οΈ HTML β‘οΈ Document
6. Event Delegation π€
Instead of adding listeners to 100 list items, add one listener to the parent <ul>. This uses bubbling to catch events from children. It's much more efficient!
AI Mentor
Confused about "JavaScript events, addEventListener, event object, bubbling, and delegation"? Ask our AI mentor for a simplified explanation.
Quiz
Quiz
Question 1 of 4Which method is used to listen for events?
Key Takeaways
β
addEventListener attaches handlers.
β
Event Object (e) holds details.
β
preventDefault stops default actions (like form submit).
β
Bubbling means events go up the tree.
β
Delegation uses bubbling to handle many elements efficiently.
What's Next?
Now let's use events to handle user input in Forms & Input Handling!
Keep coding! π