Search code examples
htmlcsstooltipclipboard.js

show a message in tool-tip separately using Clipboard.js


I followed this link Tooltip on click of a button and it was very helpful. my problem is when it changes a little, in the snippet below what should I do if I want to have two input button and have copied tool-tip message for each one separately after click on it, now in the snippet below when you click on each one it shows you two tool-tip coinside

// 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>
<button class="btn btn-primary" data-clipboard-text="1">Click me</button>


Solution

  • You should pass to your functions the button which triggered the event.

    Here is updated code:

    // Tooltip
    
    $('button').tooltip({
      trigger: 'click',
      placement: 'bottom'
    });
    
    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 clipboard = new Clipboard('button');
    
    clipboard.on('success', function(e) {
      var btn = $(e.trigger);
      setTooltip(btn,'Copied!');
      hideTooltip(btn);
    });
    
    clipboard.on('error', function(e) {
      var btn = $(e.trigger);
      setTooltip('Failed!');
      hideTooltip(btn);
    });