How to change dynamically the Bootstrap 5.0 popover?

1.7k Views Asked by At

In Bootstrap 4.0 it was possible to change the popover content (based on the selector) or to reposition it (using $tip property) dynamically

$("body").popover({
    container: 'body',
    content: 'loading...',
    html: true,
    placement: 'right',
    trigger: "hover",
    selector: '.selector1', '.selector2', ... 
 }).on('shown.bs.popover', function () {
    var this = $(event.target);
    ...
    if (this.hasClass('.selector1')) {
      var popover_method = ".../dynamic_popover_1"
    }
    ...
    $.get(popover_method, {
      ...
      },
      function(response) {
        var popover_tip = $(this.data('bs.popover').tip);
        popover_tip.find('.popover-body').empty().append(response.popover_data_json);
        if ((popover_tip.offset().top - $(window).scrollTop()) + popover_tip.height() > window.innerHeight) {
              popover_tip.css({ top: - popover_tip.height() + 5 });
        }
        ...

But how to do it in Bootstrap 5.0 where data('bs.popover') doesn't exist anymore?

1

There are 1 best solutions below

0
Carol Skelly On BEST ANSWER

You need to use vanilla JS instead. Get the popover instance in the 'shown' event using bootstrap.Popover.getInstance(myPopoverTrigger) and then you can access _config and tip as needed. For example...

var myPopoverTrigger = document.getElementById('myPopover')
var myPopover = new bootstrap.Popover(myPopoverTrigger,{
    content: 'Loading...',
    trigger: 'hover',
})

myPopoverTrigger.addEventListener('shown.bs.popover', function (e) {
    // get the popover instance
    var popover = bootstrap.Popover.getInstance(myPopoverTrigger)
    // change the content
    popover._config.content = "Done!"
    popover.setContent();
    // get the tip and chnage the position
    var tip = popover.tip
    tip.style.left = '300px';
})

Demo: https://codeply.com/p/nTTvvLo3ef