skip to Main Content

I have here a popover with a dynamic content which shows up when I click the popover button. I want to close it when I also click on another area of the page. However, the popover only closes when I click the popover button.

<a class="btn btn-danger" id="btn-post" data-html="true" data-placement="bottom" data-original-title="Post/Lock">
    Post/Lock
</a>

I do not set the data-content on my HTML code. I set it on the js

$("#btn-post").click(function() {
    $("#btn-post").attr("data-content", var_dynamic_content);
    $('#btn-post').popover('show');
});

I have tried following some codes answered in this post

How to dismiss a Twitter Bootstrap popover by clicking outside?

but nothing there seemed to work for me.

2

Answers


  1. Try this code:

    $('body').click(function() {
        $('#btn-post').popover('hide');
    });
    
    Login or Signup to reply.
  2. This answer really is similar to the one you mention in your question… Except that it is for Twitter‑Bootstrap (Bootstrap 4).

    The difference seems to be that there is no in class.

    I did not test it for all use case… But this snippet works.

    $(document).ready(function(){
    
      var var_dynamic_content = "Hello!";
    
      $("#btn-post").click(function() {
        $("#btn-post").attr("data-content", var_dynamic_content);
        $('#btn-post').popover('show');
      });
    
      $(document).click(function(e){
        // If the click occurs on #button-post or the popover itself --> exit!
        if(e.target == $("#btn-post")[0] || $(e.target).parents(".popover").length > 0){return;}
        $('#btn-post').popover('hide');
      });
    
    });  // END ready
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>
    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
    
    <a class="btn btn-danger" id="btn-post" data-html="true" data-placement="bottom" data-original-title="Post/Lock">
        Post/Lock
    </a>

    CodePen

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search