JavaScript Events
JavaScript events are actions or occurrences that happen in the browser, such as user interactions, that JavaScript can respond to. Here’s an overview of how to handle events in JavaScript.
1. Event Listeners
Event listeners are used to execute code when a specific event occurs. They can be added using the addEventListener
method.
document.getElementById('myButton').addEventListener('click', function() {
alert('Button was clicked!');
});
2. Event Types
There are various types of events, including mouse events, keyboard events, form events, and more. Common examples include click
, mouseover
, keydown
, and submit
.
document.getElementById('myInput').addEventListener('keydown', function(event) {
console.log('Key pressed: ' + event.key);
});
3. Event Object
When an event occurs, an event object is passed to the event handler function. This object contains information about the event, such as the type of event and the target element.
document.getElementById('myButton').addEventListener('click', function(event) {
console.log('Event type: ' + event.type);
console.log('Event target: ' + event.target.id);
});
4. Event Propagation
Events in JavaScript propagate through the DOM tree in two phases: capturing phase and bubbling phase. You can control this propagation using the stopPropagation
method.
document.getElementById('parentDiv').addEventListener('click', function(event) {
console.log('Parent div clicked');
}, true); // Capturing phase
document.getElementById('childDiv').addEventListener('click', function(event) {
console.log('Child div clicked');
event.stopPropagation(); // Stops event from propagating to parent
});
5. Removing Event Listeners
Event listeners can be removed using the removeEventListener
method. To remove a listener, you must pass the same function reference that was used to add it.
function handleClick() {
alert('Button was clicked!');
}
const button = document.getElementById('myButton');
button.addEventListener('click', handleClick);
// Later, to remove the event listener
button.removeEventListener('click', handleClick);