Halvor William Sanden

Target this pointer event

With e.target, this and a bit of CSS, we can cover several use cases where we need to both register a click, or event, on an element and then do something with the same element.

Single button #

Let’s say we have a single button with the id loner that we want to hide when clicking it. We can solve that in the following way by using e.target

const singleButton = document.querySelector("#loner")

singleButton.addEventListener("click", function (e) {
  e.target.hidden = true
}

We can make it shorter with this because it refers to the current context; we could just as well have written singleButton.hidden = true.

const singleButton = document.querySelector("#loner")

singleButton.addEventListener("click", function () {
  this.hidden = true
}

Multiple buttons
#

Let’s say we have a set of buttons instead. We still have to know which one has been clicked in order to hide it but it’s not efficient to give unique ids or attributes to them and query for each one. Instead, we can query and listen to events in a container. We avoid hiding the container itself by checking the type of element that is clicked.

const buttonSet = document.querySelector("#button-set")

buttonSet.addEventListener("click", function (e) {
  if (e.target.type === "button") {
    e.target.hidden = true
  }
}

If we replace e.target with this, it will stop working because this refers to the element with the button-set id, which is not a button.

Element inside buttons #

Let’s say we add an icon to our button, something to indicate removal. We use an inline SVG but start experiencing bugs, the button seems to work only half of the time. After some testing, we figure out that when we click on the icon itself, nothing is happening. The event target is no longer the button but the icon.

In the first example, we can switch from e.target to this and it’s solved. But in the multiple buttons example, we can’t do the same. Instead, we can lean on pointer-events: none.

We’ll add a class called hide to our SVG and use the CSS code as a conditional that says if any event happens on this element, let its parent element take care of it.

.hide {
  pointer-events: none;
}

Summary #

  • e.target refers to the element on which the event happens – the exact element we click.
  • this refers to the element queried for (in our case, read more about this) – as long as the event happens inside of it, we’re good.
  • CSS != 💅