How to insert close button in popover for Bootstrap

JqueryTwitter BootstrapPopover

Jquery Problem Overview


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?

Jquery Solutions


Solution 1 - Jquery

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

Solution 2 - Jquery

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

Solution 3 - Jquery

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

Solution 4 - Jquery

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

Solution 5 - Jquery

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

Solution 6 - Jquery

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>

Solution 7 - Jquery

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

Solution 8 - Jquery

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

Solution 9 - Jquery

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

Solution 10 - Jquery

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>  
 

Solution 11 - Jquery

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.

Solution 12 - Jquery

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.

Solution 13 - Jquery

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

Solution 14 - Jquery

$(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>

Solution 15 - Jquery

    $('.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.

Solution 16 - Jquery

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.

Solution 17 - Jquery

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

Solution 18 - Jquery

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

Solution 19 - Jquery

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

Solution 20 - Jquery

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

Solution 21 - Jquery

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.

Solution 22 - Jquery

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

Solution 23 - Jquery

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

Solution 24 - Jquery

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.

Solution 25 - Jquery

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

onclick="$('#my-popover').popover('hide');

Solution 26 - Jquery

<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>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDanglebz HighbreedView Question on Stackoverflow
Solution 1 - JquerydavidkonradView Answer on Stackoverflow
Solution 2 - JqueryChrisView Answer on Stackoverflow
Solution 3 - JqueryyouenView Answer on Stackoverflow
Solution 4 - JquerysonemonuView Answer on Stackoverflow
Solution 5 - JquerychunguiwView Answer on Stackoverflow
Solution 6 - JqueryAWolfView Answer on Stackoverflow
Solution 7 - JqueryBogdanioView Answer on Stackoverflow
Solution 8 - JquerymistermatView Answer on Stackoverflow
Solution 9 - Jqueryerik1337View Answer on Stackoverflow
Solution 10 - JqueryjuandiegolesView Answer on Stackoverflow
Solution 11 - JqueryAngry DanView Answer on Stackoverflow
Solution 12 - JqueryMichael AkermanView Answer on Stackoverflow
Solution 13 - JqueryDesmond LuaView Answer on Stackoverflow
Solution 14 - JquerymiiView Answer on Stackoverflow
Solution 15 - JquerymatiiiView Answer on Stackoverflow
Solution 16 - JqueryChris TennantView Answer on Stackoverflow
Solution 17 - Jqueryuser1519240View Answer on Stackoverflow
Solution 18 - JquerylontongcorpView Answer on Stackoverflow
Solution 19 - Jqueryuser3603692View Answer on Stackoverflow
Solution 20 - JquerydevoragzView Answer on Stackoverflow
Solution 21 - JqueryUkuser32View Answer on Stackoverflow
Solution 22 - JqueryJacob Cortes AmadorView Answer on Stackoverflow
Solution 23 - JqueryColinView Answer on Stackoverflow
Solution 24 - JqueryTetraDevView Answer on Stackoverflow
Solution 25 - JqueryBenView Answer on Stackoverflow
Solution 26 - JqueryArunView Answer on Stackoverflow