Show tooltip on pointer-events none element

February 21, 2021

I'm a big fan of "css only" approaches (For example) and I'm sure I'm not alone. That's why I was so exsiting to get to know the pointer-events property. With prevent-default we can "disable" non input elements such as links (even though it might not considered a good accessiblity approach) Before it came to our life we had to use code to stop the event when link is "disabled"

1document.querySelector('a').addEventListener('click', e => {
2 if (e.target.classList.contains('disabled')) {
3 e.preventDefault();
4 }
5});

What about if this a is added by code (React for example)? pretty much nightmare.

But with css

1a.disabled {
2 pointer-events: none;
3}

Magic!

Powerfull, right? Too powerful

Let's go back to our example - a "disabled" link. Usually when an element disabled, we want to show a tooltip to explain why. To simplify the example, I'm using the title property so the browser will show a native tooltip. (Once again, it's probably not accessibility compliance, but it demonstrates a use case).

Here is the code

Now try to hover the link to get the tooltip displayed. Nothing happening, right? The thing is, pointer-events: none behaviour is that

The element is never the target of pointer events

"Never" means not only "click" events but also "hover". So when element has pointer-events: none the browser doesn't apply the hover state therefor, the tooltip doesn't show.

The trick

I didn't write all of the Gibrish above just to give a sad ending. The trick is simple, to add the pointer-events: none only on :active state. This trick lavarages the browser behaviour so first it's applying :active styles and then invoking the handlers (browser and site code).

https://stackoverflow.com/a/31355432/863110

© 2022 - Moshe Feuchtwander