Event Handling
Events allow JavaScript to respond to user interactions and browser actions.
Adding Event Listeners
javascriptconst button = document.getElementById('myButton'); // Basic event listener button.addEventListener('click', function() { console.log('Button clicked!'); }); // Arrow function button.addEventListener('click', () => { console.log('Button clicked with arrow function!'); }); // Named function function handleClick(event) { console.log('Button clicked:', event.target); } button.addEventListener('click', handleClick); // Remove event listener button.removeEventListener('click', handleClick);
Event Object
javascriptfunction handleEvent(event) { console.log('Event type:', event.type); console.log('Target element:', event.target); console.log('Current target:', event.currentTarget); console.log('Mouse position:', event.clientX, event.clientY); // Prevent default behavior event.preventDefault(); // Stop event propagation event.stopPropagation(); } document.addEventListener('click', handleEvent);
Common Event Types
javascript// Mouse events element.addEventListener('click', handleClick); element.addEventListener('dblclick', handleDoubleClick); element.addEventListener('mousedown', handleMouseDown); element.addEventListener('mouseup', handleMouseUp); element.addEventListener('mouseover', handleMouseOver); element.addEventListener('mouseout', handleMouseOut); // Keyboard events document.addEventListener('keydown', function(e) { console.log('Key pressed:', e.key); console.log('Key code:', e.keyCode); if (e.key === 'Enter') { console.log('Enter key pressed'); } }); // Form events const form = document.getElementById('myForm'); form.addEventListener('submit', function(e) { e.preventDefault(); console.log('Form submitted'); }); const input = document.getElementById('myInput'); input.addEventListener('input', function(e) { console.log('Input value:', e.target.value); }); input.addEventListener('focus', () => console.log('Input focused')); input.addEventListener('blur', () => console.log('Input blurred'));
Event Delegation
javascript// Handle events on dynamically created elements const container = document.getElementById('container'); container.addEventListener('click', function(e) { if (e.target.classList.contains('delete-btn')) { e.target.parentElement.remove(); } if (e.target.classList.contains('edit-btn')) { const item = e.target.parentElement; const text = item.querySelector('.text'); text.contentEditable = true; text.focus(); } }); // Add new items dynamically function addItem(text) { const item = document.createElement('div'); item.innerHTML = ` <span class="text">${text}</span> <button class="edit-btn">Edit</button> <button class="delete-btn">Delete</button> `; container.appendChild(item); }
Custom Events
javascript// Create custom event const customEvent = new CustomEvent('userLogin', { detail: { username: 'john_doe', timestamp: Date.now() } }); // Listen for custom event document.addEventListener('userLogin', function(e) { console.log('User logged in:', e.detail.username); console.log('Login time:', new Date(e.detail.timestamp)); }); // Dispatch custom event document.dispatchEvent(customEvent); // Event emitter pattern class EventEmitter { constructor() { this.events = {}; } on(event, callback) { if (!this.events[event]) { this.events[event] = []; } this.events[event].push(callback); } emit(event, data) { if (this.events[event]) { this.events[event].forEach(callback => callback(data)); } } off(event, callback) { if (this.events[event]) { this.events[event] = this.events[event].filter(cb => cb !== callback); } } } const emitter = new EventEmitter(); emitter.on('data', (data) => console.log('Received:', data)); emitter.emit('data', 'Hello World');
Practical Examples
javascript// Modal dialog function createModal() { const modal = document.createElement('div'); modal.className = 'modal'; modal.innerHTML = ` <div class="modal-content"> <span class="close">×</span> <h2>Modal Title</h2> <p>Modal content goes here.</p> </div> `; // Close modal events modal.addEventListener('click', function(e) { if (e.target === modal || e.target.classList.contains('close')) { modal.remove(); } }); document.body.appendChild(modal); } // Drag and drop function makeDraggable(element) { let isDragging = false; let startX, startY, initialX, initialY; element.addEventListener('mousedown', function(e) { isDragging = true; startX = e.clientX; startY = e.clientY; initialX = element.offsetLeft; initialY = element.offsetTop; }); document.addEventListener('mousemove', function(e) { if (isDragging) { const deltaX = e.clientX - startX; const deltaY = e.clientY - startY; element.style.left = (initialX + deltaX) + 'px'; element.style.top = (initialY + deltaY) + 'px'; } }); document.addEventListener('mouseup', function() { isDragging = false; }); } // Form validation function validateForm(formId) { const form = document.getElementById(formId); form.addEventListener('submit', function(e) { e.preventDefault(); const inputs = form.querySelectorAll('input[required]'); let isValid = true; inputs.forEach(input => { if (!input.value.trim()) { input.classList.add('error'); isValid = false; } else { input.classList.remove('error'); } }); if (isValid) { console.log('Form is valid, submitting...'); // Submit form } }); }