event.target returns the DOM element that triggered a specific event, so we can retrieve any property/ attribute with a value.
For example, when we console.log(e.target), we can see the element’s class name, type, the position of the mouse, etc.
const button = document.querySelector(".btn");
button.addEventListener("click", buttonClick);
function buttonClick(e) {
console.log(e.target); // <button class="btn">Click me</button>
console.log(e.target.className); // btn
console.log(e.type); // click
console.log(e.offsetY); // 16
console.log(e.ctrlKey); // true if we hold down Ctrl key when we click. We can check with altKey, shiftKey.
}
Note: The difference between clientX, clientY and offsetX, offsetY
We can access the value of an event with event.target.value.
Example: We have a form, and we want to print out the value we type in.
<form class="myform">
<label>Name: </label>
<input type="text" />
</form>;
<div class="output"></div>
const itemInput = document.querySelector("input[type=text]");
itemInput.addEventListener("keydown", myEvent);
function myEvent(e) {
console.log(e.target.value);
document.querySelector(".output").innerText = e.target.value;
}
In addition to keydown, we have other event types for text: