Browser Events
What are Events?
Events are things that happen in the system you're programming. The system tells you about events so your code can react to them.
Common Event Types
- Mouse events:
click
,dblclick
,mousedown
,mouseup
,mousemove
- Keyboard events:
keydown
,keyup
,keypress
- Form events:
submit
,focus
,blur
- Window events:
load
,resize
,scroll
- Document events:
DOMContentLoaded
Adding Event Listeners
There are three main ways to add event listeners:
- HTML attribute (not recommended for modern development):
<button onclick="alert('Clicked!')">Click me</button>
- DOM property:
let button = document.querySelector('button');
button.onclick = function() {
alert('Clicked!');
};
- addEventListener method (recommended):
let button = document.querySelector('button');
button.addEventListener('click', function() {
alert('Clicked!');
});
Event Object
When an event happens, the browser creates an event object with details about the event. This object is automatically passed to the event handler:
button.addEventListener('click', function(event) {
console.log('Button clicked at coordinates: ' + event.clientX + ', ' + event.clientY);
});
Event Propagation
When an event happens on an element, it first runs the handlers on it, then on its parent, then all the way up on other ancestors. This is called "bubbling". Example:
<div id="outer">
<div id="inner">Click me</div>
</div>
<script>
document.getElementById('outer').addEventListener('click', function() {
alert('Outer div clicked');
});
document.getElementById('inner').addEventListener('click', function() {
alert('Inner div clicked');
});
</script>
If you click on the inner div, you'll see "Inner div clicked" then "Outer div clicked".
Event Delegation
Instead of assigning an event handler to each similar element, you can use event delegation. Add the event listener to a parent element and have it catch events that happen on its children.
<ul id="todo-list">
<li>Task 1</li>
<li>Task 2</li>
<li>Task 3</li>
</ul>
<script>
document.getElementById('todo-list').addEventListener('click', function(event) {
if (event.target.tagName === 'LI') {
alert('Task clicked: ' + event.target.textContent);
}
});
</script>
This way, you can handle clicks on any number of list items with just one event listener.