Search code examples
javascripthtmljquerybootstrap-4popover

Insert 'close button' in bootstrap popover


I will like to know how I can insert a 'close button' for a bootstrap popover. Additionally, I will like the popover to close automatically after x number of seconds (say 8 seconds).

<a href='#' id='example' rel='popover' data-animation="true" data-placement='left' data-content='Its so simple to create a tooltop for my website!' title='Twitter Bootstrap Popover'></a>

In my JS, I have

    $('#example').popover({
   'placement':'bottom',
    }).popover('show');

Solution

  • You'd have to override the template and attach a click function:

    $('#example').popover({
      'placement': 'auto',
      'template': '<div class="popover" role="tooltip"><div class="arrow"></div><span class="btn btn-link float-right pop-close">x</span><h3 class="popover-header"></h3><div class="popover-body"></div></div>'
    }).popover('show');
    
    $('.pop-close').click(function() {
        $('#example').popover('hide');
    });
    body {
      padding: 50px;
    }
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"></script>
    
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script>
    
    <a href='#' id='example' rel='popover' data-animation="true" data-placement='right' data-content='Its so simple to create a tooltop for my website!' title='Twitter Bootstrap Popover'></a>