atomiks / tippyjs

Tooltip, popover, dropdown, and menu library
https://atomiks.github.io/tippyjs/
MIT License
11.86k stars 520 forks source link

Allow `content` to accept return value of `null` to not open tooltip #1029

Closed vincerubinetti closed 2 years ago

vincerubinetti commented 2 years ago

Problem

I have a very simple (and I'd like to keep it that way) block of code to initialize Tippy:

tippy("[data-tooltip]", {
    content: (element) => {
      const content = element.getAttribute("data-tooltip").trim();
      // add aria label for screen readers
      element.setAttribute("aria-label", element.innerText + " - " + content);
      // remove tooltip attribute to mark element as already-tooltipped
      element.removeAttribute("data-tooltip");
      return content || null;
    },
    delay: [200, 0],
  });

Solution

If the tooltip content is an empty string or any other falsey value, the tooltip still shows, but it's blank. It would be nice to have a way, from the content function, to cancel showing the tooltip. The way I'd imagine it would work is by returning false or null.

Preemptively I want to say, "just don't put an empty data-tooltip attribute on elements" is not an acceptable solution, because in my case I'm developing a template that will be used by non-web-savvy folks, and I need to "stupid-proof" it (excuse the harsh language).

The other solution would be to filter out the empty data-tooltip elements myself before passing the elements directly to Tippy, but this adds a non-trivial amount of extra code/complexity. I know I can do a query like :not([data-tooltip='']), but that wont catch non-trimmed whitespace.

Plus, I could see this being useful for other people, who might want to conditionally show the tooltip based on the content or some other element attribute. It would be nice to have.

atomiks commented 2 years ago

You can do this

tippy('[data-tooltip]', {
  onShow(instance) {
    if (instance.props.content.trim() === '') {
      return false;
    }
  }
});
vincerubinetti commented 2 years ago

Thanks, I see that in the docs now. I did look through all the props before making this issue, but I didn't look closely at onShow I guess because I figured at that point the tooltip was already shown and it was too late.