event.target
I. What is event.target?
event.target is the element that originally triggered the event. When a user clicks a button, event.target is that button. When they type in an input, event.target is that input.
const button = document.querySelector(".btn");
button.addEventListener("click", (e) => {
console.log(e.target); // <button class="btn">Click me</button>
console.log(e.target.className); // "btn"
console.log(e.target.id); // the element's id attribute
console.log(e.type); // "click"
});
II. Mouse position
button.addEventListener("click", (e) => {
console.log(e.clientX, e.clientY); // position relative to the browser viewport
console.log(e.offsetX, e.offsetY); // position relative to the element itself
});
clientX/clientY: measured from the top-left corner of the browser windowoffsetX/offsetY: measured from the top-left corner of the element that was clicked
III. event.target.value
For form inputs, event.target.value holds the current text the user has typed.
<input type="text" class="name-input" />
<div class="output"></div>
const input = document.querySelector(".name-input");
const output = document.querySelector(".output");
input.addEventListener("input", (e) => {
output.textContent = e.target.value;
});
The input event fires on every keystroke, paste, and cut.
IV. Keyboard event properties
document.addEventListener("keydown", (e) => {
console.log(e.key); // "Enter", "a", "ArrowUp", etc.
console.log(e.code); // "KeyA", "Enter", "ArrowUp" (physical key position)
console.log(e.ctrlKey); // true if Ctrl was held
console.log(e.shiftKey);
console.log(e.altKey);
});
keypress is deprecated. Use keydown or keyup instead.
keydown fires when the key is pressed. keyup fires when it is released. Use keydown when you need to respond immediately or handle held keys.
V. Checking modifier keys
input.addEventListener("keydown", (e) => {
if (e.key === "Enter" && e.ctrlKey) {
console.log("Ctrl+Enter pressed");
}
});