Boostrap - Popover only being fired after second click

1.2k views Asked by At

I addClass/removeClass a CSS class called SiteClass dynamically (see this question for background). I bind a bootstrap popover to these like so:

$(document).ready(function(){

  $("#SiteList").on('click','a.SiteClass', function(e){
    alert('clicked');
    e.preventDefault();
    e.stopPropagation();
    var strcontent = $(this).html();
    var strTitle = 'Title for ' + strcontent;
    var strMessage = 'Foo <b>Bar</b> Baz';

    $(this).popover({
       html: true,
       title: strTitle,
       content: strMessage 
    });
  });

});

The first time I click I get the alert box 'clicked', but no popover. Subsequent clicks and the popover works.

Any clue as to why this is happening and to get the popover to fire from click 1?

2

There are 2 answers

1
elethan On BEST ANSWER

$().popover(options) simply initializes your popover. You can trigger the display of the popover with:

$(this).popover('show');

If you would like to toggle the popover on click instead, try:

$(this).popover('toggle');

I think the reason it works only after the first click in your case is that with the first click the popover is initialized with the default trigger 'click', so that subsequent clicks (but not the first click) will trigger it.

0
Alp Altunel On

after a lot of tries finally I have found out this solution and working fine:

<script>
    $(document).ready(function () {
        $(document).on("click", '#add-new', function (e) {
            e.preventDefault();
    
            $('#add-new').popover({
                placement: 'right',
                html: true,
                container: 'body',
                trigger: 'manual',
                content: function () {
                    return $('#popover_content_wrapper').html();
                },
            });
            $(this).popover('toggle');
        });
    });
</script>