Search code examples
javascripttooltiptippyjs

Change tooltip content by Tippy js v6


I'm using clipboard js to copy-paste content and there is a tooltip attached to the button by Tippy js.

But how do I change the tooltip content and make it appear for two seconds as long as the clipboard success event is fired? I cannot think of a way to change the content because I'm not using the prop but the attribute method.

Possible related doc:

https://atomiks.github.io/tippyjs/v6/constructor/

https://atomiks.github.io/tippyjs/v6/tippy-instance/

https://atomiks.github.io/tippyjs/v6/methods/

var clipboard = new ClipboardJS('.btn');

tippy('.btn', {
    placement: 'bottom',
    theme: 'clean'
});

clipboard.on('success', function(e) {
    //Change the tooltip content and show for two seconds
});
<button class="btn" data-clipboard-text="Testing...123" data-tippy-content="Tooltip">
    Copy to clipboard
</button>

<script src="https://unpkg.com/@popperjs/core@2"></script>
<script src="https://unpkg.com/tippy.js@6"></script>
<script src="https://unpkg.com/clipboard@2/dist/clipboard.min.js"></script>


Solution

  • You just need to get instance of your tippy object and call some methods on it in your event listener.

    var clipboard = new ClipboardJS('.btn');
    
    const btnTippy = tippy('.btn', {
        placement: 'bottom',
        theme: 'clean',
    })[0]; // 0-index used because tippy will return array of buttons here. You can use `querySelector` that will return only one instance if don't need array.
    
    const copiedTippy = tippy('.btn', {
        placement: 'bottom',
        theme: 'clean',
        trigger: '',
    })[0];
    
    copiedTippy.setContent('Just copied')
    
    clipboard.on('success', function (e) {
        copiedTippy.show()
        setTimeout(copiedTippy.hide, 2000) // to hide tip after 2 seconds
    });