[jquery] How to insert close button in popover for Bootstrap

JS:

$(function(){
  $("#example").popover({
    placement: 'bottom',
    html: 'true',
    title : '<span class="text-info"><strong>title</strong></span> <button type="button" id="close" class="close">&times;</button>',
    content : 'test'
  })
  $('html').click(function() {
    $('#close').popover('hide');
  });
});

HTML:

<button type="button" id="example" class="btn btn-primary" ></button>

i'm write your code isn't show your popup.

anyone come across this problem?

This question is related to jquery twitter-bootstrap popover

The answer is


<script type="text/javascript"  src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script type="text/javascript" src="jquery.popover-1.1.2.js"></script>

<script type="text/javascript">
$(function(){ 
$("#example").popover({
        placement: 'bottom',
        html: 'true',
        title : '<span class="text-info"><strong>title</strong></span> <button     type="button" id="close" class="close">&times;</button></span>',
        content : 'test'
    })


$("#close").click(function(event) {

$("#example").popover('hide');
});
});
</script>

<button type="button" id="example" class="btn btn-primary" >click</button>

Just wanted to update the answer. As per Swashata Ghosh, the following is a simpler way that worked for moi:

HTML:

<button type="button" class="btn btn-primary example">Example</button>

JS:

$('.example').popover({
   title: function() {
      return 'Popup title' +
             '<button class="close">&times</button>';
   },
   content: 'Popup content',
   trigger: 'hover',
   html: true
});

$('.popover button.close').click(function() {
   $(this).popover('toggle');
});

$popover = $el.popover({
  html: true
  placement: 'left'
  content: 'Do you want to a <b>review</b>? <a href="#" onclick="">Yes</a> <a href="#">No</a>'
  trigger: 'manual'
  container: $container // to contain the popup code
});

$popover.on('shown', function() {
  $container.find('.popover-content a').click( function() {
    $popover.popover('destroy')
  });
});

$popover.popover('show')'

I found the code below very useful (taken from https://www.emanueletessore.com/twitter-bootstrap-popover-add-close-button/):

$('[data-toggle="popover"]').popover({
  title: function(){
    return $(this).data('title')+'<span class="close" style="margin-top: -5px">&times;</span>';
  }
}).on('shown.bs.popover', function(e){
  var popover = $(this);
  $(this).parent().find('div.popover .close').on('click', function(e){
    popover.popover('hide');
  });
});

For anyone who is still a little confused:

Here is how it works to toggle the popover after you have gotten it to show, select the same button you used to trigger it and call .popover('toggle') on it.

In this case, for closing the popover the code would be:

$('#example').popover('toggle');


I found other answers were either not generic enough, or too complicated. Here is a simple one that should always work (for bootstrap 3):

$('[data-toggle="popover"]').each(function () {
    var button = $(this);
    button.popover().on('shown.bs.popover', function() {
        button.data('bs.popover').tip().find('[data-dismiss="popover"]').on('click', function () {
            button.popover('toggle');
        });
    });
});

Then just add attribute data-dismiss="popover" in your close button. Also make sure not to use popover('hide') elsewhere in your code as it hides the popup but doesn't properly sets its internal state in bootstrap code, which will cause issues next time you use popover('toggle').


FWIW, here's the generic solution that I'm using. I'm using Bootstrap 3, but I think the general approach should work with Bootstrap 2 as well.

The solution enables popovers and adds a 'close' button for all popovers identified by the 'rel="popover"' tag using a generic block of JS code. Other than the (standard) requirement that there be a rel="popover" tag, you can put an arbitrary number of popovers on the page, and you don't need to know their IDs -- in fact they don't need IDs at all. You do need to use the 'data-title' HTML tag format to set the title attribute of your popovers, and have data-html set to "true".

The trick that I found necessary was to build an indexed map of references to the popover objects ("po_map"). Then I can add an 'onclick' handler via HTML that references the popover object via the index that JQuery gives me for it ("p_list['+index+'].popover(\'toggle\')"). That way I don't need to worry about the ids of the popover objects, since I have a map of references to the objects themselves with a JQuery-provided unique index.

Here's the javascript:

var po_map = new Object();
function enablePopovers() {
  $("[rel='popover']").each(function(index) {
    var po=$(this);
    po_map[index]=po;
    po.attr("data-title",po.attr("data-title")+
    '<button id="popovercloseid" title="close" type="button" class="close" onclick="po_map['+index+'].popover(\'toggle\')">&times;</button>');
    po.popover({});
  });
}
$(document).ready(function() { enablePopovers() });

this solution let me easily put a close button on all the popovers all across my site.


Sticky on hover, HTML:

<a href="javascript:;" data-toggle="popover" data-content="Vivamus sagittis lacus vel augue laoreet rutrum faucibus." title="Lorem Ipsum">...</a>

Javascript:

$('[data-toggle=popover]').hover(function(e) {
  if( !$(".popover").is(':visible') ) {
      var el = this;
      $(el).popover('show');
      $(".popover > h3").append('<span class="close icon icon-remove"></span>')
                        .find('.close').on('click', function(e) {
                            e.preventDefault();
                            $(el).popover('hide');
                        }
      );
  }
});

enter image description here

The following is what i just used in my project .And hope it can help you

<a id="manualinputlabel" href="#" data-toggle="popover" title="weclome to use the sql quer" data-html=true  data-original-title="weclome to use the sql query" data-content="content">example</a>


$('#manualinputlabel').click(function(e) {
              $('.popover-title').append('<button id="popovercloseid" type="button" class="close">&times;</button>');
              $(this).popover();

          });

      $(document).click(function(e) {
         if(e.target.id=="popovercloseid" )
         {
              $('#manualinputlabel').popover('hide');                
         }

      });

As a very simple solution to this, I did the following:

1) Add the following CSS:

.sub_step_info .popover::after {
    content:url('/images/cross.png');
    position:absolute;
    display:inline-block;
    top:15px;
    right:5px;
    width:15px;
    text-align:center;
    cursor:pointer;
}

2) Set data-trigger="manual" on the popover trigger element

3) Then based on https://github.com/twbs/bootstrap/issues/16802:

$('[data-trigger="manual"]').click(function() {
    $(this).popover('toggle');
}).blur(function() {
    $(this).popover('hide');
}); 

This uses the basis that anywhere on the popover is clickable but by focusing on the cross you'll encourage the behaviour you're after.


Try this:

$(function(){
  $("#example")
      .popover({
      title : 'tile',
      content : 'test'
    })
    .on('shown', function(e){
      var popover =  $(this).data('popover'),
        $tip = popover.tip();

      var close = $('<button type="button" class="close" aria-label="Close"><span aria-hidden="true">&times;</span></button>')
        .click(function(){
          popover.hide();
        });
      $('.popover-title', $tip).append(close);
    });
});

Rather than adding the button as a string of markup, it's much easier if you have a jQuery wrapped button because then you can bind much more neatly. This is indeed sadly missing from the Bootstrap code, but this workaround works for me, and actually could be expanded to apply to all popovers if desired.


I was running into the problem of the tooltip doing some funky stuff when the close button became clicked. To work around this I used a span instead of using a button. Also, when the close button was clicked I would have to click the tooltip twice after it closed in order to get it to open again. To work around this I simply used the .click() method, as seen below.

<span tabindex='0' class='tooltip-close close'>×</span>

$('#myTooltip').tooltip({
    html: true,
    title: "Hello From Tooltip",
    trigger: 'click'
});    

$("body").on("click", ".tooltip-close", function (e) {
    else {
        $('.tooltip').remove();
        $('#postal-premium-tooltip').click();
    }
});

I needed to find something that would work for multiple popovers and in Bootstrap 3.

Here's what I did:

I had multiple elements I wanted to have a popover work for, so I didn't want to use ids.

The markup could be:

<button class="btn btn-link foo" type="button">Show Popover 1</button>
<button class="btn btn-link foo" type="button">Show Popover 2</button>
<button class="btn btn-link foo" type="button">Show Popover 3</button>

The content for the save and close buttons inside the popover:

var contentHtml = [
    '<div>',
        '<button class="btn btn-link cancel">Cancel</button>',
        '<button class="btn btn-primary save">Save</button>',
    '</div>'].join('\n');

and the javascript for all 3 buttons:

This method works when the container is the default not attached to body.

$('.foo').popover({
    title: 'Bar',
    html: true,
    content: contentHtml,
    trigger: 'manual'
}).on('shown.bs.popover', function () {
    var $popup = $(this);
    $(this).next('.popover').find('button.cancel').click(function (e) {
        $popup.popover('hide');
    });
    $(this).next('.popover').find('button.save').click(function (e) {
        $popup.popover('hide');
    });
});

When the container is attached to 'body'

Then, use the aria-describedby to find the popup and hide it.

$('.foo').popover({
    title: 'Bar',
    html: true,
    content: contentHtml,
    container: 'body',
    trigger: 'manual'
}).on('shown.bs.popover', function (eventShown) {
    var $popup = $('#' + $(eventShown.target).attr('aria-describedby'));
    $popup.find('button.cancel').click(function (e) {
        $popup.popover('hide');
    });
    $popup.find('button.save').click(function (e) {
        $popup.popover('hide');
    });
});

Previous examples have two main drawbacks:

  1. The 'close' button needs in some way, to be aware of the ID of the referenced-element.
  2. The need of adding on the 'shown.bs.popover' event, a 'click' listener to the close button; which is also not a good solution because of, you would then be adding such listener each time the 'popover' is shown.

Below is a solution which has not such drawbacks.

By the default, the 'popover' element is inserted immediately after the referenced-element in the DOM (then notice the referenced-element and the popover are immediate sibling elements). Thus, when the 'close' button is clicked, you can simply look for its closest 'div.popover' parent, and then look for the immediately preceding sibling element of such parent.

Just add the following code in the 'onclick' handler of the 'close button:

$(this).closest('div.popover').popover('hide');

Example:

var genericCloseBtnHtml = '<button onclick="$(this).closest(\'div.popover\').popover(\'hide\');" type="button" class="close" aria-hidden="true">&times;</button>';

$loginForm.popover({
    placement: 'auto left',
    trigger: 'manual',
    html: true,
    title: 'Alert' + genericCloseBtnHtml,
    content: 'invalid email and/or password'
});

$(function(){ 
  $("#example").popover({
    placement: 'bottom',
    html: 'true',
    title : '<span class="text-info"><strong>title!!</strong></span> <button type="button" id="close" class="close">&times;</button></span>',
    content : 'test'
  })

  $(document).on('click', '#close', function (evente) {
    $("#example").popover('hide');
  });
  $("#close").click(function(event) {
    $("#example").popover('hide');
  });
});

<button type="button" id="example" class="btn btn-primary" >click</button>

I have struggle with this one and this is the simplest way to do it, 3 lines of js:

  1. Add a cross in the title of the popover
  2. use the js snippet to show the popover and to close by clicking the header
  3. Use a bit of css to make it nice

enter image description here

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  // This is to overwrite the boostrap default and show it allways_x000D_
  $('#myPopUp').popover('show');_x000D_
  // This is to destroy the popover when you click the title_x000D_
  $('.popover-title').click(function(){_x000D_
    $('#myPopUp').popover('destroy');_x000D_
  });_x000D_
});
_x000D_
@import "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css";_x000D_
_x000D_
/* Just to align my example */_x000D_
.btn {_x000D_
  margin: 90px auto;_x000D_
  margin-left: 90px;_x000D_
}_x000D_
_x000D_
/* Styles for header */_x000D_
.popover-title {_x000D_
  border: 0;_x000D_
  background: transparent;_x000D_
  cursor: pointer;_x000D_
  display: inline-block;_x000D_
  float: right;_x000D_
  text-align: right; _x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
    _x000D_
<button id="myPopUp" class="btn btn-success" data-toggle="popover" data-placement="top" data-title="×" data-content="lorem ipsum content">My div or button or something with popover</button>  _x000D_
 
_x000D_
_x000D_
_x000D_


The trick is to get the current Popover with .data('bs.popover').tip():

$('#my_trigger').popover().on('shown.bs.popover', function() {
    // Define elements
    var current_trigger=$(this);
    var current_popover=current_trigger.data('bs.popover').tip();

    // Activate close button
    current_popover.find('button.close').click(function() {
        current_trigger.popover('hide');
    });
});

You need to make the markup right

<button type="button" id="example" class="btn btn-primary">example</button>

Then, one way is to attach the close-handler inside the element itself, the following works :

$(document).ready(function() {
    $("#example").popover({
        placement: 'bottom',
        html: 'true',
        title : '<span class="text-info"><strong>title</strong></span>'+
                '<button type="button" id="close" class="close" onclick="$(&quot;#example&quot;).popover(&quot;hide&quot;);">&times;</button>',
        content : 'test'
    });
});  

Put this in your title popover constructor...

'<button class="btn btn-danger btn-xs pull-right"
onclick="$(this).parent().parent().parent().hide()"><span class="glyphicon
glyphicon-remove"></span></button>some text'

...to get a small red 'x' button on top-right corner

//$('[data-toggle=popover]').popover({title:that string here})

I've checked many of the mentioned code examples and for me the approach from Chris is working perfectly. I've added my code here to have a working demo of it.

I have tested it with Bootstrap 3.3.1 and I haven't tested it with an older version. But it's definitely not working with 2.x because the shown.bs.popover event was introduced with 3.x.

_x000D_
_x000D_
$(function() {_x000D_
  _x000D_
  var createPopover = function (item, title) {_x000D_
                       _x000D_
        var $pop = $(item);_x000D_
        _x000D_
        $pop.popover({_x000D_
            placement: 'right',_x000D_
            title: ( title || '&nbsp;' ) + ' <a class="close" href="#">&times;</a>',_x000D_
            trigger: 'click',_x000D_
            html: true,_x000D_
            content: function () {_x000D_
                return $('#popup-content').html();_x000D_
            }_x000D_
        }).on('shown.bs.popover', function(e) {_x000D_
            //console.log('shown triggered');_x000D_
            // 'aria-describedby' is the id of the current popover_x000D_
            var current_popover = '#' + $(e.target).attr('aria-describedby');_x000D_
            var $cur_pop = $(current_popover);_x000D_
          _x000D_
            $cur_pop.find('.close').click(function(){_x000D_
                //console.log('close triggered');_x000D_
                $pop.popover('hide');_x000D_
            });_x000D_
          _x000D_
            $cur_pop.find('.OK').click(function(){_x000D_
                //console.log('OK triggered');_x000D_
                $pop.popover('hide');_x000D_
            });_x000D_
        });_x000D_
_x000D_
        return $pop;_x000D_
    };_x000D_
_x000D_
  // create popover_x000D_
  createPopover('#showPopover', 'Demo popover!');_x000D_
_x000D_
  _x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>_x000D_
_x000D_
<button class="btn btn-primary edit" data-html="true" data-toggle="popover" id="showPopover">Show</button>_x000D_
_x000D_
<div id="popup-content" class="hide">_x000D_
    <p>Simple popover with a close button.</p>_x000D_
    <button class="btn btn-primary OK">OK</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_


For me this is the simplest solution to add a close button in a popover.

HTML:

    <button type="button" id="popover" class="btn btn-primary" data-toggle="popover" title="POpover" data-html="true">
                    Show popover
    </button>

    <div id="popover-content" style="display:none"> 
       <!--Your content-->
       <button type="submit" class="btn btn-outline-primary" id="create_btn">Create</button>
       <button type="button" class="btn btn-outline-primary" id="close_popover">Cancel</button>  
    </div>

Javascript:

    document.addEventListener("click",function(e){
        // Close the popover 
        if (e.target.id == "close_popover"){
                $("[data-toggle=popover]").popover('hide');
            }
    });

    $('.tree span').each(function () {
        var $popOverThis = $(this);
        $popOverThis.popover({
            trigger: 'click',
            container: 'body',
            placement: 'right',
            title: $popOverThis.html() + '<button type="button" id="close" class="close" ">&times;</button>',
            html: true,
            content: $popOverThis.parent().children("div.chmurka").eq(0).html()
        }).on('shown.bs.popover', function (e) {
            var $element = $(this);
            $("#close").click(function () {
                $element.trigger("click");
            });
        });
    });

When you click element and show your popup, next you can raise event shown.bs.popover where in this you get element in which trigger click to close your popover.


This works with multiple popovers and I also added a little big of extra JS to handle the z-index issues that happen with overlapping popovers:

http://jsfiddle.net/erik1337/fvE22/

JavaScript:

var $elements = $('.my-popover');
$elements.each(function () {
    var $element = $(this);

    $element.popover({
        html: true,
        placement: 'top',
        container: $('body'), // This is just so the btn-group doesn't get messed up... also makes sorting the z-index issue easier
        content: $('#content').html()
    });

    $element.on('shown.bs.popover', function (e) {
        var popover = $element.data('bs.popover');
        if (typeof popover !== "undefined") {
            var $tip = popover.tip();
            zindex = $tip.css('z-index');

            $tip.find('.close').bind('click', function () {
                popover.hide();
            });

            $tip.mouseover(function (e) {
                $tip.css('z-index', function () {
                    return zindex + 1;
                });
            })
                .mouseout(function () {
                $tip.css('z-index', function () {
                    return zindex;
                });
            });
        }
    });
});

HTML:

<div class="container-fluid">
    <div class="well popover-demo col-md-12">
        <div class="page-header">
             <h3 class="page-title">Bootstrap 3.1.1 Popovers with a close button</h3>

        </div>
        <div class="btn-group">
            <button type="button" data-title="Popover One" class="btn btn-primary my-popover">Click me!</button>
            <button type="button" data-title="Popover Two" class="btn btn-primary my-popover">Click me!</button>
            <button type="button" data-title="Popover Three (and the last one gets a really long title!)" class="btn btn-primary my-popover">Click me!</button>
        </div>
    </div>
</div>
<div id="content" class="hidden">
    <button type="button" class="close">&times;</button>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
</div>

CSS:

/* Make the well behave for the demo */
 .popover-demo {
    margin-top: 5em
}
/* Popover styles */
 .popover .close {
    position:absolute;
    top: 8px;
    right: 10px;
}
.popover-title {
    padding-right: 30px;
}

This is a working solution based on @Chris answer above, but fixed so that upon subsequence clicks of the trigger element, you don't have to click the element twice.

Using .popover('hide) manually messes up bootstraps internal state, as noted in the comments.

var closePopover = function(eventShown) {
   // Set the reference to the calling element
   var $caller = $('#' + this.id);

   // Set the reference to the popover
   var $popover = $('#' + $(eventShown.target).attr('aria-describedby'));

       // Unbind any pre-existing event handlers to prevent duplicate clicks
       $popover.find('.popover-close').off('click');

       // Bind event handler to close button
       $popover.find('.popover-close').on('click', function(e) {

          // Trigger a click on the calling element, to maintain bootstrap's internal state
          $caller.trigger('click');
        });
 }

$('.popoverTriggerElement').popover({
   trigger: 'click'
})
.on('shown.bs.popover', closePopover)

Now, you can use the close button without duplicating the click events, and keeping bootstraps internal state in check so it works as expected.


Here's a "cheat" solution:

Follow the usual directions for a dismissable popup.

Then slap an 'X' in the box with CSS.

CSS:

.popover-header::after {
    content: "X";
    position: absolute;
    top: 1ex;
    right: 1ex;
}

JQUERY:

$('.popover-dismiss').popover({
    trigger: 'focus'
});

HTML:

<a data-toggle="popover" data-trigger="focus" tabindex="0"  title="Native Hawaiian or Other Pacific Islander" data-content="A person having origins in any of the original peoples of Hawaii, Guam, Samoa, or other Pacific Islands.">?</a>

Technically speaking that makes it dismissable if someone clicks something other than the "X" but that's not a problem in my scenario at least.


Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to twitter-bootstrap

Bootstrap 4: responsive sidebar menu to top navbar CSS class for pointer cursor How to install popper.js with Bootstrap 4? Change arrow colors in Bootstraps carousel Search input with an icon Bootstrap 4 bootstrap 4 responsive utilities visible / hidden xs sm lg not working bootstrap.min.js:6 Uncaught Error: Bootstrap dropdown require Popper.js Bootstrap 4 - Inline List? Bootstrap 4, how to make a col have a height of 100%? Bootstrap 4: Multilevel Dropdown Inside Navigation

Examples related to popover

Changing the width of Bootstrap popover bootstrap popover not showing on top of all elements How to insert close button in popover for Bootstrap HTML inside Twitter Bootstrap popover Contain form within a bootstrap popover? How to dismiss a Twitter Bootstrap popover by clicking outside? How do I use popover from Twitter Bootstrap to display an image? How to position a Bootstrap popover? Changing the position of Bootstrap popovers based on the popover's X position in relation to window edge? Is it possible to use a div as content for Twitter's Popover