Building Your Learning Module...
Getting things ready for you!
Find videos you like?
Save to resource drawer for future reference!
When an event fires, JavaScript automatically creates an event object containing details about what happened. Access it through the first parameter of your event handler!
e, evt, or event).const parent = document.querySelector('#parent');
const child = document.querySelector('#child');
parent.addEventListener('click', function(e) {
// target: element that was actually clicked
// currentTarget: element with the listener
console.log('Target:', e.target.id);
console.log('CurrentTarget:', e.currentTarget.id);
});const button = document.querySelector('#btn');
function handleEvent(e) {
console.log('Event type:', e.type);
}
button.addEventListener('click', handleEvent);
button.addEventListener('mouseenter', handleEvent);
button.addEventListener('mouseleave', handleEvent);const form = document.querySelector('#myForm');
form.addEventListener('submit', function(e) {
e.preventDefault(); // Stop form submission
const input = document.querySelector('#email');
console.log('Email:', input.value);
console.log('Form NOT submitted to server');
});const box = document.querySelector('#box');
box.addEventListener('mousemove', function(e) {
console.log('clientX:', e.clientX); // Viewport
console.log('clientY:', e.clientY);
console.log('pageX:', e.pageX); // Document
console.log('pageY:', e.pageY);
console.log('offsetX:', e.offsetX); // Element
console.log('offsetY:', e.offsetY);
});const box = document.querySelector('#box');
box.addEventListener('mousedown', function(e) {
// 0 = left, 1 = middle, 2 = right
if (e.button === 0) {
console.log('Left click');
} else if (e.button === 2) {
console.log('Right click');
}
});const input = document.querySelector('#input');
input.addEventListener('keydown', function(e) {
console.log('key:', e.key); // 'a', 'A', '1'
console.log('code:', e.code); // 'KeyA', 'Digit1'
console.log('altKey:', e.altKey);
console.log('ctrlKey:', e.ctrlKey);
console.log('shiftKey:', e.shiftKey);
});e.target - Element that triggered evente.currentTarget - Element with listenere.type - Event type (click, keydown, etc.)e.preventDefault() - Stop default behaviore.stopPropagation() - Stop bubblinge.clientX/Y - Position in viewporte.pageX/Y - Position in documente.offsetX/Y - Position in elemente.button - Which button (0/1/2)e.key - Character pressed (a, A, 1)e.code - Physical key (KeyA)e.altKey - Alt pressed?e.ctrlKey - Ctrl pressed?e.shiftKey - Shift pressed?e.target.value - Input valuee.target.checked - Checkbox statee.target.selectedIndex - Select indexe.preventDefault() on form submit events to handle data with JavaScript instead of page reload!