carbon-components-svelte icon indicating copy to clipboard operation
carbon-components-svelte copied to clipboard

[Question] How to add a Tooltip to an Input component label?

Open sanzoghenzo opened this issue 2 years ago • 3 comments

Forgive me for the stupid question, but I can't seem to find a good way to display tooltips inside a form.

The ideal is having the tooltips appear hovering over the various inputs, but I can live with having a Tooltip with triggerText in place of the labels.

This is the best I could do:

<Form>
  <TextInput>
    <span slot="labelText">
      <Tooltip triggerText="Label">
        <p>long text explaining the input</p>
      </Tooltip>
    </span>
  </TextInput>

  <Toggle>
    <span slot="labelText">
      <Tooltip triggerText="Switch">
        <p>another long text for explanation</p>
      </Tooltip>
    </span>
  </Toggle>
</Form>

But when I click on the tooltip icons:

  • the TextInput get focused and the tooltip disappears quckly (I have to keep the mouse down to read the text)
  • the Toggle gets toggled

Is this because of the on:click forwarded event in the parent div of those components?

Is there a workaround for this?

sanzoghenzo avatar Mar 24 '22 17:03 sanzoghenzo

I'll need to investigate this further, but as a workaround I'd suggest using TooltipDefinition as a workaround:

https://svelte.dev/repl/25e72a9ab7d74f3c839e14a6c1271fdf?version=3.46.4

<script>
  import { TextInput, TooltipDefinition } from "carbon-components-svelte";
</script>

<TextInput>
  <svelte:fragment slot="labelText">
    <TooltipDefinition align="start" tooltipText="Tooltip content">Label</TooltipDefinition>
  </svelte:fragment>
</TextInput>

metonym avatar Mar 25 '22 13:03 metonym

Nice, This is exactly what I need!

I tried with the TooltipDefinition before learning about the label/labelText slots, so I didn't get far.

If only I knew about this before converting all the TooltipDefinitions into Tooltips 😅

sanzoghenzo avatar Mar 25 '22 16:03 sanzoghenzo

Note that this is invalid HTML and may break the association of the label with the input, as now the label contains an additional button for the tooltip.

Content for the label is specified as:

Phrasing content, but with no descendant labelable elements unless it is the element's labeled control, and no descendant label elements.

(Just tested this scenario with a screen reader and focusing the input still reads the label (and the tooltip), which is good. Just clicking the label will no longer focus the input.)

brunnerh avatar Apr 02 '22 18:04 brunnerh