Search code examples
javascriptjqueryhtmlbootstrap-4popover

Activate Popover on Hover and click anywhere to close


I'm using Bootstrap 4 and wanted to use the popover where I can hover to active and close it when you click anywhere.

I also want to make the link work inside the popover. Anyone have any idea how to make it work or what am I missing?

$(document).ready(function(){
    $('[data-toggle="popover"]').popover({
        placement : 'top',
        trigger : 'hover',
        html : true
    });
});

$('body').on('click', function (e) {
    //only buttons
    if ($(e.target).data('toggle') !== 'popover'
        && $(e.target).parents('.popover.in').length === 0) { 
        $('[data-toggle="popover"]').popover('hide');
    }
});
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">

<a href="mailto:[email protected]" data-toggle="popover" title="Popover" data-content="test content <a href='' title='test add link'>link on content</a>" data-original-title="test title">Test</a>

<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>


Solution

  • For rendering the link, use html: true and to show/hide the popover, you can use the following code:

    $(document).ready(function() {
      $('[data-toggle="popover"]').popover({
        placement: 'top',
        html: true
      });
    
      $('[data-toggle="popover"]').on("mouseenter", function() {
        $(this).popover('show');
      });
      
      $('body').on('click', function(e) {
        $('[data-toggle=popover]').each(function() {
          if (!$(this).is(e.target) && $(this).has(e.target).length === 0 && $('.popover').has(e.target).length === 0) {
            $(this).popover('hide');
          }
        });
      });
    });
    html, body{ height: 100%; }
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" />
    
    <a href="mailto:[email protected]" data-toggle="popover" title="Popover" data-content="test content <a href='#' title='test add link'>link on content</a>" data-original-title="test title">Test</a>
    
    <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>