⚡
Event Handling
Intermediate
90 XP
35 min
Lesson Content
Event Handling
Events are actions that happen in the browser, like clicks, key presses, or form submissions. JavaScript can listen for these events and respond to them.
Common Events
- click - Mouse click
- mouseover - Mouse enters element
- mouseout - Mouse leaves element
- keydown/keyup - Keyboard key pressed/released
- submit - Form submitted
- change - Input value changed
- load - Page loaded
Event Listeners
// Method 1: addEventListener (recommended)
button.addEventListener('click', function() {
alert('Button clicked!');
});
// Method 2: Inline handler
button.onclick = function() {
alert('Clicked!');
};
// Arrow function
button.addEventListener('click', () => {
console.log('Clicked');
});Event Object
button.addEventListener('click', function(event) {
console.log(event.target); // The element that was clicked
console.log(event.type); // 'click'
});Example Code
Create interactive elements with event listeners
<!DOCTYPE html>
<html><head><title>Events</title></head><body>
<button id="btn">Click Me</button>
<p id="output">Click the button</p>
<input type="text" id="input" placeholder="Type something">
<p id="text-output"></p>
<script>
// Click event
const btn = document.getElementById('btn');
btn.addEventListener('click', function() {
document.getElementById('output').textContent = 'Button was clicked!';
document.getElementById('output').style.color = 'green';
});
// Input event
const input = document.getElementById('input');
input.addEventListener('input', function(event) {
document.getElementById('text-output').textContent =
'You typed: ' + event.target.value;
});
</script>
</body></html>Expected Output:
Click the button
Study Tips
- •Read the theory content thoroughly before practicing
- •Review the example code to understand key concepts
- •Proceed to the Practice tab when you're ready to code