s0rin
s0rin

Reputation: 156

How to change dynamically the Bootstrap 5.0 popover?

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?

Upvotes: 1

Views: 2301

Answers (1)

Carol Skelly
Carol Skelly

Reputation: 362520

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

Upvotes: 2

Related Questions