Event Handling in JavaScript
Key Concepts
- Event Listeners
- Event Types
- Event Object
- Event Propagation
Event Listeners
Event listeners are functions that wait for a specific event to occur on an element. They are attached using the addEventListener
method, which takes two parameters: the event type and the function to be executed when the event occurs.
Example:
let button = document.getElementById("myButton"); button.addEventListener("click", function() { alert("Button clicked!"); });
Event Types
Event types are the specific actions or occurrences that trigger event listeners. Common event types include click
, mouseover
, keydown
, submit
, and load
. Each event type corresponds to a different user interaction or browser action.
Example:
let input = document.getElementById("myInput"); input.addEventListener("keydown", function(event) { console.log("Key pressed: " + event.key); });
Event Object
The event object is automatically passed to the event handler function. It contains information about the event, such as the type of event, the target element, and details about the user's interaction. Common properties include type
, target
, keyCode
, and clientX/clientY
.
Example:
let link = document.getElementById("myLink"); link.addEventListener("mouseover", function(event) { console.log("Event type: " + event.type); console.log("Target element: " + event.target.tagName); });
Event Propagation
Event propagation refers to the order in which event handlers are called when an event occurs on nested elements. There are two types of event propagation: bubbling and capturing. In bubbling, the event is first handled by the innermost element and then propagated to outer elements. In capturing, the event is first handled by the outermost element and then propagated to inner elements.
Example:
let outer = document.getElementById("outer"); let inner = document.getElementById("inner"); outer.addEventListener("click", function() { console.log("Outer element clicked"); }); inner.addEventListener("click", function(event) { console.log("Inner element clicked"); event.stopPropagation(); // Stops the event from propagating further });