JavaScript Events
🎯 Introduction to Events
Events are actions or occurrences that happen in the browser, such as clicks, key presses, or page loads. JavaScript can detect these events and execute code in response.
Common Event Types:
- Mouse Events: click, dblclick, mousedown, mouseup
- Keyboard Events: keydown, keyup, keypress
- Form Events: submit, change, focus, blur
- Window Events: load, resize, scroll
Event Handler Methods:
addEventListener()- Recommended methodonclick- Inline property (limited)element.onclick = function()- DOM property
📋 The Event Object
When an event occurs, the browser creates an event object containing information about the event. This object is passed to the event handler function.
Common Properties:
type- Event type (click, keydown, etc.)target- Element that triggered eventcurrentTarget- Element with listenerclientX/clientY- Mouse coordinates
Keyboard Properties:
key- Character valuecode- Physical key codectrlKey/shiftKey/altKey- Modifier keys
Event Methods:
preventDefault()- Prevent default actionstopPropagation()- Stop event flowstopImmediatePropagation()- Stop all handlers
🌊 Event Flow: Bubbling & Capturing
Events in the DOM have three phases: capturing, target, and bubbling. Understanding this flow is crucial for complex event handling.
Event Flow Phases:
- Capturing Phase: Window → Document → ... → Parent
- Target Phase: Event reaches target element
- Bubbling Phase: Target → Parent → ... → Window
Flow Control Methods:
stopPropagation()- Stops event flowstopImmediatePropagation()- Stops all handlerspreventDefault()- Prevents default action
🎪 Event Delegation Pattern
Event delegation is a technique where you attach a single event listener to a parent element instead of multiple listeners to child elements. This is more efficient and works with dynamically added elements.
✅ Event Delegation Benefits:
- Performance: Single listener instead of many
- Memory: Less memory usage
- Dynamic Content: Works with elements added later
- Cleaner Code: Centralized event handling
📋 Event Reference
Mouse Events:
click- Single clickdblclick- Double clickmousedown- Button pressedmouseup- Button releasedmousemove- Mouse movedmouseenter- Enter elementmouseleave- Leave element
Keyboard Events:
keydown- Key pressedkeyup- Key releasedkeypress- Character input
Form Events:
submit- Form submittedchange- Input value changedinput- Input value changingfocus- Element focusedblur- Element lost focus
Window Events:
load- Page loadedresize- Window resizedscroll- Page scrolledbeforeunload- Before page unload