As a TypeScript developer, you may have come across a situation where you need to disable pointer events on an element, but still want to observe clicks on that element. This can be a common requirement when working with interactive UI components or overlays. In this blog post, we will explore two solutions to achieve this functionality.

Solution 1: Using a transparent overlay

One way to achieve this is by adding a transparent overlay on top of the element with the pointer-events: none CSS property. This overlay will capture the clicks and propagate them to the underlying element.

const overlay = document.createElement('div');
overlay.style.pointerEvents = 'none';
overlay.style.position = 'absolute';
overlay.style.top = '0';
overlay.style.left = '0';
overlay.style.width = '100%';
overlay.style.height = '100%';
element.appendChild(overlay);

overlay.addEventListener('click', (event) => {
  // Handle the click event
});

In the above code snippet, we create a new

element and set its pointer-events CSS property to none. We position the overlay absolutely and cover the entire area of the underlying element. Finally, we attach a click event listener to the overlay to handle the clicks.

Solution 2: Using event delegation

Another approach is to use event delegation to observe clicks on the parent element and check if the target element matches the desired element. This way, even if the desired element has pointer-events: none, we can still detect clicks on it.

element.addEventListener('click', (event) => {
  if (event.target === desiredElement) {
    // Handle the click event
  }
});

In the above code snippet, we attach a click event listener to the parent element and check if the event.target matches the desired element. If it does, we handle the click event accordingly.

Conclusion

Disabling pointer events on an element while still observing clicks can be achieved using either a transparent overlay or event delegation. Both solutions provide a way to handle clicks on elements with pointer-events: none. Choose the solution that best fits your use case and implement it in your TypeScript project.