JavaScript Events - Exercise 1
Use addEventListener() with the click event. The callback runs every time the button is clicked. The example shows the same rule with a small handler that can run in the browser.
const button = document.querySelector('#saveButton');
button.addEventListener('click', () => {
console.log('Saved');
});The event object describes what happened. Its target property points to the element that dispatched the event. The example shows the same rule with a small handler that can run in the browser.
button.addEventListener('click', (event) => {
console.log(event.target.textContent);
});Listen for focus and update the input or a nearby message. Keep the handler focused on the event and use the event object when you need more details.
const input = document.querySelector('#name');
input.addEventListener('focus', () => {
input.classList.add('is-active');
});Use the mouseenter event for a handler that runs when the pointer enters the element. Keep the handler focused on the event and use the event object when you need more details.
const card = document.querySelector('.card');
card.addEventListener('mouseenter', () => {
card.classList.add('highlight');
});The input event fires whenever the value changes, including typing, pasting, or autofill. Keep the handler focused on the event and use the event object when you need more details.
input.addEventListener('input', (event) => {
document.querySelector('#preview').textContent = event.target.value;
});Listen for submit on the form. Call preventDefault() when JavaScript should handle the data instead of navigating. The example shows the same rule with a small handler that can run in the browser.
form.addEventListener('submit', (event) => {
event.preventDefault();
console.log('Form handled in JavaScript');
});Keyboard events expose the pressed key through event.key. Keep the handler focused on the event and use the event object when you need more details.
document.addEventListener('keydown', (event) => {
if (event.key === 'Escape') console.log('Closed');
});Keep a reference to the named handler, then pass that same reference to removeEventListener(). Keep the handler focused on the event and use the event object when you need more details.
function handleClick() { console.log('Clicked'); }
button.addEventListener('click', handleClick);
button.removeEventListener('click', handleClick);After an event reaches its target, it can travel back up through ancestor elements. A parent listener can observe the event during this bubbling phase.
list.addEventListener('click', (event) => {
console.log(event.target.textContent);
});Call stopPropagation() when a handler should prevent the event from continuing to ancestor listeners. Use it only when that propagation change is intentional.
button.addEventListener('click', (event) => {
event.stopPropagation();
});