How to insert close button in popover for Bootstrap
Asked Answered
V

28

80

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?

Varus answered 16/11, 2012 at 8:40 Comment(0)
A
91

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'
    });
});  
Arvid answered 16/11, 2012 at 9:22 Comment(15)
It works! Wonder why this is not core-integrated into Bootstrap ?Prefix
@Sebf, bootstrap is intended to be as light as possible, many issues is meant to be solved on the implementation layer. Yeah, some "missing" parts is baffling ;-)Arvid
It should be noted that this solution doesn't use the native data-dismiss feature that is already included in bootstrap's code. It creates new code to solve a problem that is already solved. I use the native code in my answer below.Orgy
@Orgy data-dismiss="popover" inplace of the onclick doesn't work. This is a well documented problem.Haematoxylon
Works, but not great style. For those in a production workflow, I would recommend using underscore.js template function. Keep your html out of your javascriptEnterogastrone
Using inline HTML and JavaScript events in the popover title is a pretty bad practice. It might work, but it will give you headaches later on.Philomenaphiloo
@Mario Fink (and Robert Kotcher) - totally agree off course. But this was how you could implement the desired functionality in twitter bootstrap 2.x, now the intended way fails. I simply answer the question.Arvid
I just noticed that doing $(elm).popover('hide') sometimes (I am not sure if all the time) leaves the popup where it is and just adds a .fade class which makes opacity 0. This would cause users not being able to select text etc. A finer solution is to use $(elm).popover('toggle').Marijo
Hey @SwashataGhosh, what version of bootstrap? This is an "old" answer, targeting bootstrap 2.x - havent tested it on boostrap 3.0Arvid
@Arvid Yes, I tested it on bootstrap 3.0. You can see the implementation on this theme I made github.com/swashata/ipt-knowledgebase-theme-wpMarijo
For me the example above only worked by replacing the double quotes (&quot;) with single quotes (&#39;)Jeanejeanelle
This is a really interesting solution. Because I have 350 of these on the same page, I used onclick="$(this).parents(&quot;div.popover&quot;).siblings(&quot;a.popover-link&quot;).popover(&quot;hide&quot;);" (where .popover-link represents the class used to toggle the popover) to generically close the specific popover. This may not work if you change the container.Monda
Does this solution require 2 clicks to re-open the popover for you? Then add the following fix: $('body').on('hidden.bs.popover', function (e) { $(e.target).data("bs.popover").inState.click = false; }); github.com/twbs/bootstrap/issues/16732#issuecomment-165229037Helladic
Hey @EdJ, that is an very important detail! I am pretty sure inState.click is added to BS3 after 2012.Arvid
This will requiring clicking the trigger element twice to popup again. Use my solution below to solve that: https://mcmap.net/q/259083/-how-to-insert-close-button-in-popover-for-bootstrapGrouch
C
33

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');
    });
});
Cusack answered 10/11, 2013 at 15:28 Comment(4)
Small improvement: popup.find('button.cancel').on('click',function(e) {...}Aureolin
when I click on cancel link, it closes the popover. But I have to click twice on popover-trigger link as it does not open popover in first click.Misery
There's predefined class .close with hover effect, so inserting close button into title or content is as easy as <span class=close>&times;</span>.Stadia
@NizamKazi Use my solution below to solve that: https://mcmap.net/q/259083/-how-to-insert-close-button-in-popover-for-bootstrapGrouch
K
29

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').

Kauri answered 23/1, 2015 at 9:27 Comment(4)
For some reason, using Bootstrap 3, .popover('toggle'); never does anything for me, where as .popover('hide'); does work. Other than that, this solution is my favorite. Thank you!Sharilyn
Wouldn't that bind the click event on every popover-show-event, resulting in multiple bindings?Unni
@pduersteler this is old code, but it's used in production, so I'm pretty sure it works. I guess bootstrap creates a new popover, and therefore a new close button, each time the button is clicked. If there was multiple events on the close button, it would toggle multiple times, and I would have noticed the bug (hopefully). Let me know if you can confirm an issue though. On second thought, maybe that's why I had an issue with popover('hide') that would not destroy the popover but just hide it?Kauri
this should be $(button.data('bs.popover').tip).find('[data-dismiss="popover"]') in modern bootstrap (>= 4?)Clammy
D
21

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'
});
Depurative answered 9/6, 2014 at 0:34 Comment(2)
Wow, nice and simple solution. Works for me.Nephology
With Bootstrap 4.3 I had to add sanitize: false to the popover optionsJaimie
P
15

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');                
         }

      });
Prosimian answered 15/7, 2013 at 12:58 Comment(3)
Hey, thanks for your anwser! Would you know how to vertically center the &times; symbol within the h3.popover-title object?Selfforgetful
Worked well, but I had the same issue with vertical alignment. I added my own class to the close button with line-height: 0.7 !important; and looked goodFulgurate
when I click on cancel link, it closes the popover. But I have to click twice on popover-trigger link as it does not open popover in first clickRb
B
10

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.

$(function() {
  
  var createPopover = function (item, title) {
                       
        var $pop = $(item);
        
        $pop.popover({
            placement: 'right',
            title: ( title || '&nbsp;' ) + ' <a class="close" href="#">&times;</a>',
            trigger: 'click',
            html: true,
            content: function () {
                return $('#popup-content').html();
            }
        }).on('shown.bs.popover', function(e) {
            //console.log('shown triggered');
            // 'aria-describedby' is the id of the current popover
            var current_popover = '#' + $(e.target).attr('aria-describedby');
            var $cur_pop = $(current_popover);
          
            $cur_pop.find('.close').click(function(){
                //console.log('close triggered');
                $pop.popover('hide');
            });
          
            $cur_pop.find('.OK').click(function(){
                //console.log('OK triggered');
                $pop.popover('hide');
            });
        });

        return $pop;
    };

  // create popover
  createPopover('#showPopover', 'Demo popover!');

  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>

<button class="btn btn-primary edit" data-html="true" data-toggle="popover" id="showPopover">Show</button>

<div id="popup-content" class="hide">
    <p>Simple popover with a close button.</p>
    <button class="btn btn-primary OK">OK</button>
</div>
Bryon answered 5/12, 2014 at 0:7 Comment(1)
I guess it must be $cur_pop.popover('hide');Ecospecies
P
5

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');
    });
});
Probst answered 30/4, 2014 at 16:14 Comment(0)
M
4

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');
});
Mathre answered 31/10, 2013 at 20:48 Comment(0)
O
4

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;
}
Origami answered 15/5, 2014 at 21:12 Comment(0)
A
4

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

$(document).ready(function() {
  // This is to overwrite the boostrap default and show it allways
  $('#myPopUp').popover('show');
  // This is to destroy the popover when you click the title
  $('.popover-title').click(function(){
    $('#myPopUp').popover('destroy');
  });
});
@import "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css";

/* Just to align my example */
.btn {
  margin: 90px auto;
  margin-left: 90px;
}

/* Styles for header */
.popover-title {
  border: 0;
  background: transparent;
  cursor: pointer;
  display: inline-block;
  float: right;
  text-align: right; 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    
<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>  
 
Aarhus answered 1/12, 2016 at 12:26 Comment(1)
why the cross button is not getting navigated with tab ?Royall
N
3

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.

Nidifugous answered 21/1, 2015 at 17:37 Comment(1)
Worked for me best, just need to update BS names: 'shown' -> 'shown.bs.popover' data('popover') -> data('bs.popover')Lethalethal
B
3

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.

Bellona answered 15/6, 2018 at 21:54 Comment(0)
A
1
$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')'
Allomerism answered 13/3, 2013 at 5:25 Comment(0)
B
1
$(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>
Butler answered 25/4, 2013 at 4:26 Comment(0)
E
1
    $('.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.

Ellynellynn answered 21/11, 2013 at 11:0 Comment(0)
B
1

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.

Bitterweed answered 27/11, 2013 at 20:56 Comment(0)
H
1

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');
  });
});
Haystack answered 11/9, 2017 at 20:10 Comment(0)
C
1

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();
    }
});
Carpentry answered 11/11, 2019 at 21:29 Comment(1)
using $('.tooltip').remove(); worked for meEngstrom
C
1

I use Bootstrap 5 and wanted to have a button inside a Popover, but the button just wouldn't do anything.

After trying different solutions, it turned out that the only problem was the sanitize-option of the popover.

So I had to add sanitize: false to the popover options, to get the button to work.

Clownery answered 7/7, 2022 at 11:8 Comment(1)
This is a simple trick that unfortunately ChatGPT doesn't seem to know about.Karleen
C
0

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');
                        }
      );
  }
});
Cholecystitis answered 20/5, 2013 at 6:55 Comment(0)
T
0

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})
Trilobite answered 9/5, 2014 at 3:32 Comment(0)
M
0

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');

Magnetic answered 28/1, 2016 at 18:11 Comment(0)
D
0

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.

Disguise answered 16/4, 2018 at 14:52 Comment(0)
T
0

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');
            }
    });
Tessi answered 16/3, 2019 at 12:40 Comment(0)
G
0

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.

Grouch answered 18/11, 2019 at 22:2 Comment(0)
W
0

For a specific popover, you can just add a onclick event on the close button:

onclick="$('#my-popover').popover('hide');
Wivern answered 20/4, 2021 at 18:33 Comment(0)
D
0

There were so many answers, but I had these constraints and no answer addressed them all:

  • compatible with bootstrap 5
  • works with multiple popovers on a page (i.e., no single hardcoded id and keeps the actual element popover data attributes simple)
  • doesn't suffer from the problem of having to reclick the element twice
  • allows me to click a link in the popover content without closing
  • doesn't require separate css, but looks decent

all-in-one code:

$(document).ready(function() {
  $('[data-bs-toggle="popover"]').popover({
    html: true,
  }).on('shown.bs.popover', function(e) {
    // get the dom element that the popover points to
    var el = $(e.target);
    // get the popover dom obj
    var po = $('#' + el.attr('aria-describedby'));
    // get the title
    var poh = po.find('.popover-header');
    poh.append('<sup class="popover-close ms-3" style="cursor:pointer;">&times;</sup>');

    // get the close button that we just added
    var cb = poh.find('.popover-close');

    // get the bootstrap popover obj
    var bpo = bootstrap.Popover.getInstance(e.target);

    cb.on('click', function(e) {
      bpo.hide();
    });
  });
});
<html>

<head>
  <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
</head>

<body>
  <span data-bs-toggle="popover" data-bs-content="my content" id="random_id" title="my title">click this text</span>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
</body>

</html>
Davidadavidde answered 3/2, 2023 at 15:3 Comment(0)
A
-4
<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>
Appurtenance answered 16/11, 2012 at 9:11 Comment(1)
Sry, but that will never work. #close only exists when the popover is active, click is never bound. Try alert($("#close").length); (it alerts 0)Arvid

© 2022 - 2025 — McMap. All rights reserved.