event.target JavaScript

I. What is an event.target?

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

  • e.clientX: get the position on the x-axis when we click. It counts the position from the width of the browser window.
  • e.clientY: Similar to clientX, but get the position on the y-axis when we click.
  • e.offsetX and e.offsetY: get the position from the actual element.

II. event.target.value

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;
}

III. Event type for text

In addition to keydown, we have other event types for text:

  • keyup
  • keypress
  • focus
  • blur
  • cut
  • paste
  • input: Event fires whenever we do anything with the input.