0

I want to combine Bootstrap 4, ClipboardJS and Tooltips (PopperJS).

My Code is working so far: When I click on a button, the value of the field „data-clipboard-text“ is saved in the clipboard. But the tooltips don’t show up and don’t hide, because I don’t know how to put in the right button into the function.

HTML (there’s a list of n buttons with different values in the field „data-clipboard-text“):

<button class="btn btn-secondary btn-sm" data-clipboard-text="25" data-toggle="tooltip" data-placement="top">Copy to clipboard</button>
<button class="btn btn-secondary btn-sm" data-clipboard-text="51" data-toggle="tooltip" data-placement="top">Copy to clipboard</button>
<button class="btn btn-secondary btn-sm" data-clipboard-text="178" data-toggle="tooltip" data-placement="top">Copy to clipboard</button>
[…] 
<button class="btn btn-secondary btn-sm" data-clipboard-text="2" data-toggle="tooltip" data-placement="top">Copy to clipboard</button>

JS:

<script type="text/javascript">

    // tooltip: enable all items with data-toggle=“tooltip“
    $(function () {
        $('[data-toggle="tooltip"]').tooltip({trigger:'click'})
    });

    function setTooltip(btn, message) {
        $(btn).tooltip('hide')
        .attr('data-original-title', message)
        .tooltip('show');
    }

    function hideTooltip(btn) {
        setTimeout(function() {
            $(btn).tooltip('hide');
            }, 1000);
    }

    // clipboard
    var btns = document.querySelectorAll('button');
    var clipboard = new ClipboardJS(btns);

    clipboard.on('success', function(e) {
        setTooltip(btns, 'Copied!');
        console.log(e);
    });

    clipboard.on('error', function(e) {
        hideTooltip(btns);
        console.log(e);
    });

</script>
myyvee
  • 95
  • 9

1 Answers1

0

The right solution for this is the following code.

HTML:

<button class="btn btn-secondary btn-sm" data-clipboard-text="22" data-toggle="tooltip" title="Kopiert!" data-placement="top">Copy to clipboard</button>

JS:

jQuery(document).ready(function () {

    $('[data-toggle="tooltip"]').tooltip({trigger:'click', delay: {show: 200, hide: 100}});

    function setTooltip(btn) {
        $(btn).tooltip('show');
    }

    $(function () {
        $(document).on('shown.bs.tooltip', function (e) {
            setTimeout(function () {
                $(e.target).tooltip('hide');
            }, 2000);
        });
    });

    var btns = document.querySelectorAll('button');
    var clipboard = new ClipboardJS(btns);

    clipboard.on('success', function(e) {
        setTooltip($(this).btns);
        console.log(e);
    });

});

Successfully tested - all buttons with data-attribute "tooltip" will be first activated. After that, if you click on any (!) button, its value of data-clipboard-text is copied and after 2 seconds (value changeable) all tooltips are closed again, even if you click on more than one button. Yeah!

myyvee
  • 95
  • 9