Tooltip on click of a button

user5368737 picture user5368737 · Jun 13, 2016 · Viewed 55.6k times · Source

I'm using clipboard.js to copy some text from a textarea, and that's working fine, but I want to show a tooltip saying "Copied!" if it was successfully copied like they do in the example given on their website.

Here's an example of it working without showing a tooltip: https://jsfiddle.net/5j50jnhj/

Answer

Zeno Rocha picture Zeno Rocha · Jun 13, 2016

Clipboard.js creator here. So Clipboard.js is not opinionated about user feedback which means it doesn't come with a tooltip solution.

But here's an example of how you can integrate it with Bootstrap's Tooltip.

// Tooltip

$('button').tooltip({
  trigger: 'click',
  placement: 'bottom'
});

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

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

// Clipboard

var clipboard = new Clipboard('button');

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

clipboard.on('error', function(e) {
  setTooltip('Failed!');
  hideTooltip();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/1.5.10/clipboard.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet"/>

<button class="btn btn-primary" data-clipboard-text="1">Click me</button>