Callback function after tooltip / popover is created with twitter bootstrap?

Callback function after tooltip / popover is created with twitter bootstrap?

I want to manipulate a tooltip or popover after it is created with twitter bootstrap. As far as i know there isn’t a build in way to do this.
$(‘#selector’).popover({
placement: ‘bottom’
});

For example lets say i want to move the created tooltip up 5px and left 5px from it’s calculated location. Any ideas on the best way to do this?
This is what i’d like to do:
$(‘#selector’).popover({
placement: ‘bottom’,
callback: function(){
alert(‘Awesome’);
}
});

Solutions/Answers:

Solution 1:

Works for tooltip:

var tmp = $.fn.tooltip.Constructor.prototype.show;
$.fn.tooltip.Constructor.prototype.show = function () {
  tmp.call(this);
  if (this.options.callback) {
    this.options.callback();
  }
}

this.$('#selector').tooltip({ 
  placement: 'top', 
  callback: function() { 
    alert('hello') 
  } 
});

Solution 2:

Maybe this wasn’t available when the previous answers were given but as of 2016, you can attach events to popovers (functionally equivalent to a callback).

eg

$('#myPopover').on('shown.bs.popover', function () {
  // do something…
})

Events include:

  • show.bs.popover
  • shown.bs.popover
  • hide.bs.popover
  • hidden.bs.popover
  • inserted.bs.popover

Ref bootstrap docs

Solution 3:

This answer was posted just to clarify things as requested by crafter and contains code from the comment by Marquez.

Related:  How do you change the width and height of Twitter Bootstrap's tooltips?

First you extend Bootstrap’s popover to handle a callback option.

var tmp = $.fn.popover.Constructor.prototype.show;
$.fn.popover.Constructor.prototype.show = function() {
    tmp.call(this); if (this.options.callback) {
        this.options.callback();
    }
}

Then you add a callback property to your option object and assign it with an anonymous function.

$('#popover-foo').popover({
    content: 'Hello world',
    callback: function () {
        alert('Hello');
    }
});

Solution 4:

Other Workaround:

  1. Use the show.bs.popover or shown.bs.popover listeners
  2. In the callback, the ‘shown’ event data links to the target which holds the popover ID, from here you could do the rest

    $('body')
    .popover(options)
    .on('shown.bs.popover', function(shownEvent) {
            update_popover_data(shownEvent);
    });
    

Callback function:

    function update_popover_data(shownEvent) {
         var id = $(shownEvent.target).attr('aria-describedby');
         $('#'+id).html('Your New Popover Content');
    }

References