javascriptjquerypopoverbootstrap-5

How do you create and modify popover in Bootstrap 5 using jquery?


Does someone know how I can create and add data to bootstrap 5 popover via javascript/jquery?

With bootstrap 3 I was able to do this:

$('#element').popover({ placement : 'left', trigger : 'focus', html: true });
let content_template = `<h1>Hello World!</h1>`;
$('#element').data('bs.popover').options.content = content_template;

But I can't figure out how I can do the same with bootstrap 5. The documentation doesn't mention anything about this. Does anyone know how popovers are managed in BS5?


Solution

  • You need to get instance of popover and then use popover_instance._config.content ="some message" to set new content inside your popover .

    Demo Code :

    new bootstrap.Popover(document.querySelector('[data-bs-toggle]'), {
      placement: 'left',
      trigger: 'focus',
      html: true
    })
    //get instance
    var popover_instance = bootstrap.Popover.getInstance(document.querySelector('[data-bs-toggle]'))
    let content_template = `<h1>Hello World!</h1>`;
    popover_instance._config.content = content_template;//set content
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
    <button type="button" class="btn btn-lg btn-danger" data-bs-toggle="popover" title="Popover title">Click to toggle popover</button>