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>