Search code examples
javascriptvue.jsvuetify.jstooltipdynamically-generated

Dynamically create tooltip for an element


I am trying to show a tooltip when user selects random text on the page - think of annotating text.

I was able to dynamically create v-tooltip component. I have selected element in JS, but having trouble wrapping it with v-tooltip component. I was able to wrap it, but the tooltip is positioned to the top of the page, not on the wrapped element itself. I am also not sure my approach is the best one either.

Here is a JSFiddle example: https://jsfiddle.net/6xk7zLv9/

Is there better way to dynamically generate Vue components and insert into the DOM? How can I correctly attach tooltip to the selected element.


Solution

  • You need to specify a side prop (top/bottom/left/right) on the tooltip.

    The activator slot is also optional, instead you can use the position-x and position-y props to place it wherever you want without replacing DOM elements: https://codepen.io/kaelwd/pen/LYWLxVe?editors=1010

    window.getSelection().getRangeAt(0).getBoundingClientRect() will give you the position of the current selection: https://codepen.io/kaelwd/pen/poewRaE?editors=1010
    If you want to get really fancy you can call getClientRects instead and have the tooltip follow the end of the selection: https://codepen.io/kaelwd/pen/vYxZgjb?editors=1010

    https://developer.mozilla.org/en-US/docs/Web/API/Window/getSelection https://developer.mozilla.org/en-US/docs/Web/API/Selection/getRangeAt https://developer.mozilla.org/en-US/docs/Web/API/Range/getClientRects