Search code examples
bootstrap-4twitter-bootstrap-tooltiptooltipster

Bootstrap tooltip to show on click but hide on mouse out


I have a button that copies text into clipboard, I need to show bootstraps tooltip when user clicks on the button to indicate the text was copied successfully.

<a onclick="copyText()" role="button" data-toggle="tooltip" data-theme="dark" data-trigger="click" title="Link Copied">
    <i class="fas fa-share-alt"></i>
</a> 

However I don't want the user to click once again on the button to hide the tooltip because that would unnecessarily copy the text another time. Rather I'd like simply to hide the tooltip when the user clicks away or move the cursor out of the button.

Is it possible to do that?


Solution

  • You can use Bootstrap Methods and Events APIs as follows.

    function copyText() {
      // do something...
    }
    
    $(function() {
      $('[data-toggle="tooltip"]').tooltip();
      $('[data-toggle="tooltip"]').on('show.bs.tooltip', function() {
        $(this).on('mouseleave', function() {
          $(this).tooltip('hide');
        });
      });
    });
    body {
      padding: 3rem
    }
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.2/css/all.min.css" integrity="sha512-HK5fgLBL+xu6dm/Ii3z4xhlSUyZgTT9tuc/hSrtw6uzJOvgRr2a9jyxxT1ely+B+xFAmJKVSTbpM/CuL7qxO8w==" crossorigin="anonymous" />
    <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx" crossorigin="anonymous"></script>
    
    <a onclick="copyText()" role="button" data-toggle="tooltip" data-theme="dark" data-trigger="click" title="Link Copied">
      <i class="fas fa-share-alt"></i>
    </a>
    
    <hr>
    
    <h4>It supports multiple elements</h4>
    
    <a onclick="copyText()" role="button" data-toggle="tooltip" data-theme="dark" data-trigger="click" title="Link Copied">
      <i class="fas fa-share-alt"></i>
    </a>
    <a onclick="copyText()" role="button" data-toggle="tooltip" data-theme="dark" data-trigger="click" title="Link Copied">
      <i class="fas fa-share-alt"></i>
    </a>
    <a onclick="copyText()" role="button" data-toggle="tooltip" data-theme="dark" data-trigger="click" title="Link Copied">
      <i class="fas fa-share-alt"></i>
    </a>