Joel Alvarez Myrrie
Joel Alvarez Myrrie

Reputation: 416

Bootstrap popover, close button

Im did the following popover: https://jsfiddle.net/ca4h0a0q/

<a class='danger' data-placement='above' title="Popover Title" href='#'>Click</a>
<div id="popover_content_wrapper" style="display: none">
 <button class="close">
  x
  </button>
  <div>This is your div content</div> 
</div>

Javascript:

$(document).ready(function(){
    $("body").on("click",".close",function(){
    $(".danger").trigger("click");  
  });

  $('.danger').popover({ 
    html : true,
    content: function() {
      return $('#popover_content_wrapper').html();
    }
  });
});

For closing the popover, due to this bug: https://github.com/twbs/bootstrap/issues/16732 I had to trigger a click event on the button that opened it. I don't like this solution much. Any better way of doing this?

Upvotes: 0

Views: 1937

Answers (3)

mkours
mkours

Reputation: 510

When you know the ID (or class or anything else to identify) of the source element:

$('#<id>').popover('hide'); 

or

$('#<id>').popover('dispose');

will work fine.

If you add the class popover_show at creation, like

$(info.jsEvent.srcElement).addClass('popover_show');

you can use the .popover_show class to close/dispose all open popovers:

$('.popover_show').popover('dispose'); 

or

$('.popover_show').popover('dispose'); 

The rough way to delete all popovers (if you have trouble or like to clean up).

$('.popover').remove(); 

(if you have nested popovers, manuell added DOM-Elements to Popover, hidden elements ...)

Upvotes: 0

Miguel Coder
Miguel Coder

Reputation: 1949

I got it working this way.

<div id="popover_content_wrapper" style="display: none">
  <button class="close" onclick="$('.danger').popover('hide').trigger('click')">
    x
  </button>
<div>This is your div content</div> 

And the js...

$(document).ready(function(){
  $('.danger').popover({ 
    html : true,
    content: function() {
      return $('#popover_content_wrapper').html();
    }
  });
});

Upvotes: 1

jeanfrg
jeanfrg

Reputation: 2351

I would replace this

$("body").on("click",".close",function(){
    $(".danger").trigger("click");  
});

With this

$("body").on("click",".close",function(){
    $(this)
        .closest("a.danger")
        .trigger("click");  
});

More on closest: http://api.jquery.com/closest/

This way if you have multiple popovers or an element with the class danger they won't be triggered too.

Upvotes: 0

Related Questions